Im trying to run the below code that compares the user and group and confirms if the user is a member of the group. But i'm unable to export the output to an excel.
$users = gc .\UserInfo.csv
$groups = gc .\groupInfo.csv
$outputFilePath = "C:\Users\salesid.csv"
$members = foreach ($group in $groups) {Get-ADGroupMember -Identity $group -Recursive | Select -ExpandProperty SamAccountName
foreach ($user in $users) {
If ($members -contains $user) {
$a = write-host "$user is a member of $group"
} Else {
$a = Write-Host "$user is not a member of $group"
}
}
}
$a| Export-Csv .\Output.csv -NoTypeInformation
Read-Host -Prompt "Press Enter to exit"
To output as CSV file you can open in Excel, you need to output objects in the loop, not strings:
$users = Get-Content .\UserInfo.csv
$groups = Get-Content .\groupInfo.csv
$outputFilePath = "C:\Users\salesid.csv"
# loop through the groups; collect all output in $result
$result = foreach ($group in $groups) {
$members = Get-ADGroupMember -Identity $group -Recursive | Select-Object -ExpandProperty SamAccountName
# loop through the users array and outout objects that get collected in variable $result
foreach ($user in $users) {
[PsCustomObject]@{
Group = $group
User = $user
IsMember = ($members -contains $user) # True or False in the output
}
}
}
$result | Export-Csv -Path $outputFilePath -UseCulture -NoTypeInformation
If the amount of data is too large to handle in memory, the following code should work, BUT will be slower because of all the extra disk-write actions:
# loop through the groups
foreach ($group in $groups) {
$members = Get-ADGroupMember -Identity $group -Recursive | Select-Object -ExpandProperty SamAccountName -Unique
# loop through the users array and outout objects that get collected in variable $result
foreach ($user in $users) {
$isMember = "$user is {0}a member of $group" -f $(if ($members -contains $user) {''} else {'NOT '})
[PsCustomObject]@{
Group = $group
User = $user
IsMember = $isMember
} | Export-Csv -Path $outputFilePath -UseCulture -Append -NoTypeInformation
}
}
switch -UseCulture
makes sure the delimiter character is the same your local Excel will understand. This might be the default comma, but perhaps your system uses the semi-colon as list seoarator