Reputation: 61
I'm trying to make a script returning AD users ID, Display Name and Group memberships based on an input file and export the result to another file.
However, the group membership information seems to get lost in the process.
Any ideas?
My current script:
$Result = @()
ForEach ($_ in gc userlist.csv)
{
$User = Get-ADUser $_ -Properties DisplayName, SamAccountName, LastLogonDate | Select DisplayName, SamAccountName, LastLogonDate
$Groups = Get-ADPrincipalGroupMembership $_ | Select Name
# So far it seems to work
$Properties = @{
UserID = (@($User.SamAccountName) -join ',')
Name = (@($User.DisplayName) -join ',')
LastLogonDate = (@($User.LastLogonDate) -join ',')
Groups = (@($Groups.Name) -join ',')
}
# By this time, Groups doesn't return any information
$Result += New-Object psobject -Property $Properties
}
$Result | Select-Object Name, UserID, Groups, LastLogonDate | Export-Csv -NoTypeInformation -Path output.csv
Upvotes: 2
Views: 88
Reputation: 23395
Here's what I think might work:
$Result = @()
ForEach ($User in gc userlist.csv) {
$UserDetails = Get-ADUser $User -Properties DisplayName, SamAccountName, LastLogonDate | Select DisplayName, SamAccountName, LastLogonDate
$Groups = Get-ADPrincipalGroupMembership $User | Select Name
$Properties = @{
UserID = $UserDetails.SamAccountName
Name = $UserDetails.DisplayName
LastLogonDate = $UserDetails.LastLogonDate
Groups = ($Groups.Name -join '; ')
}
$Result += New-Object psobject -Property $Properties
}
$Result | Select-Object Name, UserID, Groups, LastLogonDate | Export-Csv -NoTypeInformation -Path output.csv
$_
will probably work its not particularly good practice to manually set that variable so i've changed it to $user.@()
for each of the properties as well as your joining them with ,
. I'm not sure why this is necessary, except perhaps with the Groups
property, but in order to then not confuse the CSV result, i've joined these with a ;
instead.Upvotes: 1