KSpinnato
KSpinnato

Reputation: 37

Domain Admin Cleanup with Foreach-Object

I'm in the process of cleaning up my inherited Domain Admins group and remove service accounts that are no longer needed. I'm trying to pull the group membership of the Domain Admins group and feed it into a Get-ADUser, with little success.

$name = Get-ADGroupMember "domain admins" | select -ExpandProperty Name
Foreach-Object {
  Get-ADUser -Filter { Name -Like "$name"} -Properties * | FT Name, LastLogonDate
}

If I run the Get-ADGroupMember by itself it works. If I run the Get-ADUser with a name from the list (instead of the $name variable) it works. But when I attempt to tie them together it does not work.

Upvotes: 0

Views: 148

Answers (2)

Matt
Matt

Reputation: 46710

I am glad you were able to make it work but I would like to offer some advice. First don't use -Properties * when all you really needed was LastLogonDate. You are pulling more data than you need to. Also you don't even need the ForEach loop since Get-Aduser will accept the pipeline input very nicely.

Get-ADGroupMember "domain admins" | Get-ADUser -Properties LastLogonDate |
  Select Name,LastLogonDate 

or if you really want console output, as supposed to standard output

Get-ADGroupMember "domain admins" | Get-ADUser -Properties LastLogonDate |
  Format-Table Name,LastLogonDate -AutoSize

Upvotes: 2

KSpinnato
KSpinnato

Reputation: 37

Thanks @EBGreen, your comment pointed me in the right direction. I am able to get what I need with the following:

Get-ADGroupMember "domain admins" | select -ExpandProperty SamAccountName | % {
    $name=$_
    Get-ADUser $_ -Properties *
} | FT Name, LastLogonDate -AutoSize

Upvotes: 1

Related Questions