TroggleDorf
TroggleDorf

Reputation: 420

Formatting MemberOf string in Get-AdUser

I am running a simple script to list all of my domain users, the last time they logged on, whether or not their accounts are enabled, and what groups they are a member of.

I have two problems. One, the lastLogon value is not a date/time format. Two, more importantly, the MemberOf column lists everything about the group object, when all I really want is the CN value. Moreover, for users in several groups, some of the information is truncated.

How do I fix this?

This is the script I am running:

Get-AdUser -Filter * -Properties Name,Description,Enabled,lastLogon,MemberOf | FT Name,Description,Enabled,lastLogon,MemberOf -autosize | format-list | out-string -width 4096 | Out-File C:\test.txt

Upvotes: 1

Views: 6794

Answers (1)

EBGreen
EBGreen

Reputation: 37730

So, first I would suggest outputting the info as a CSV rather than try to get it out into a text file. Trying to get all the accounts on one line is very impractical. For instance my user object is in 133 different groups in my environment.

Second, I would give up on making this a one liner and use an actual script to build custom objects that you can the export to CSV. Here is some top of the head code to get you going in the right direction. I'll make it actual functional tested code later if I have a chance.

$results = @()
$users = Get-ADUser -Filter * -Properties Name,Description,Enabled,lastLogon,MemberOf
foreach($user in $users){
    $lastlogon = [datetime]::FromFileTime($user.lastlogon)
    foreach($group in $user.MemberOf){
        $temp = New-Object PSCustomObject -Property @{'Name' = $user.Name;
                                                      'Description' = $user.Description;
                                                      'Enabled' = $user.Enabled;
                                                      'LastLogon' = $lastlogon;
                                                      'Group' = '';
        }
        $temp.Group = $group.Split(',')[0]
        $results += $temp
    }
}
$results | Export-CSV C:\Temp\SomeFile.csv -NoTypeInformation

Tested it and that code worked for me.

Upvotes: 2

Related Questions