0

I have a script to get users information from the Active directory. It will first get the names of the users then store it in a variable before passing it through a foreach loop to get the details of each account. The script can be run but the CSV file is empty. The following is the script. Appreciate the help.

PROCESS{
$path = "C:\Users\Administrator\CSVReports"
     
    $reportdate = Get-Date -Format ddmmyyyy 
 
    $csvreportfile = $path + "\ALLADUsers_$reportdate.csv" 

$Admins = (Get-ADGroupMember -Identity Administrators | select-object Name)

Foreach( $i in $Admins){
$UserDetails= Get-ADUser -Filter "Name -eq '$i'" -Properties * | select-object DisplayName, samaccountName, Enabled, Created, LastLogonDate | sort-object -Property LastLogonDate
}

$UserDetails | Export-Csv -Path $csvreportfile -NoTypeInformation     
}
Keith
  • 27
  • 6
  • your `Select-Object` is sending out an object with one property. your filter is NOT expanding that property. i suggest you change the `S-O` call to use `-ExpandProperty` so that you get the VALUE of the property instead of an object that contains the property. [*grin*] – Lee_Dailey Dec 08 '20 at 08:05
  • Thanks, that fixed it. But now im facing another issue, There is only 1 entry in the file. I checked the value of my $Admins and there are 3 names. Is there an issue with my foreach loop? – Keith Dec 08 '20 at 09:07
  • `Get-ADGroupMember` can return users, groups, and computers, so you can't simply use `Get-ADUser` on the objects without being sure the object **is** a user object. Also, using `Get-ADUser` with a filter like `"Name -eq '$i'"` is really asking for trouble since names are not unique in the domain. The objects you get from `Get-ADGroupMember` already have the perfect dentity property, named distinguishedName, so use that. Although the properties you want differ a bit, the question is the same as [this one](https://stackoverflow.com/questions/63181574/powershell-get-user-information-from-ad-list) – Theo Dec 08 '20 at 09:07
  • @Keith - you are overwriting the `$UserDetails` in your `foreach` loop. then you use that to write to your CSV file ... and it will only have the last result from your loop since you threw away all the previous ones. [*grin*] – Lee_Dailey Dec 08 '20 at 09:15
  • Thanks! This was really helpful. I will look through it and update my script. – Keith Dec 08 '20 at 09:28

0 Answers0