Maybe something like this would help you:
Param (
[ValidateScript({Test-Path -Path $_ -PathType Leaf})]
[String]$ImportFile = 'S:\Test\Input_Test\GroupNames.txt',
[ValidateScript({Test-Path -Path $_ -PathType Container})]
[String]$SaveFolder = 'S:\Test\Input_Test'
)
$Groups = Get-Content $ImportFile
ForEach ($Group in $Groups) {
Get-ADGroupMember -Identity $Group -Recursive |
Select-Object -ExpandProperty SamAccountName |
Out-File -LiteralPath (Join-Path $SaveFolder "$Group.txt")
}
You can fill the file GroupNames.txt with the groups you want and it will create one file for each group.
Content GroupNames.txt:
Group 1
Group 2
If you want to go a bit more advanced, you can create a function like this:
Function Export-ADGroupMembersToFile {
Param (
[Parameter(Mandatory)]
[ValidateScript({Test-Path -Path $_ -PathType Leaf})]
[String]$ImportFile,
[Parameter(Mandatory)]
[ValidateScript({Test-Path -Path $_ -PathType Container})]
[String]$SaveFolder
)
$Groups = Get-Content $ImportFile
$OutFile = Join-Path $SaveFolder "Groups_$(Get-Date -F 'yyyyMMddHHmm').txt"
Write-Verbose "Output will be saved to file '$OutFile'"
ForEach ($Group in $Groups) {
Write-Verbose "GroupName: $Group"
"`n", $Group, ('-'*40) | Out-File -LiteralPath $OutFile -Append
$Members = Get-ADGroupMember -Identity $Group -Recursive |
Select-Object -ExpandProperty SamAccountName
foreach ($M in $Members) {
Write-Verbose "Adding user $M"
Out-File -InputObject $M -LiteralPath $OutFile -Append
}
}
}
Export-ADGroupMembersToFile -ImportFile 'S:\Test\Input_Test\GroupNames.txt' -SaveFolder 'S:\Test\Input_Test' -Verbose
This will output one file that contains all the GroupNames.