Reputation: 3
I've got the following Powershell script working which searches for an AD users last name and am not getting the foreach loop output results I'm expecting. Server 2008 R2 Domain and Powershell v3
If I have UserA LastName1 and UserB LastName1, the results are being output like this:
Please Enter a UserName: LastName1
User Name: UserB LastName1 UserA LastName1
Login Name: UserB.LastName1 UserA.LastNam1
Year Created: 2012 2014
User Name: UserB LastName1 UserA LastName1
Login Name: UserA.LastName1 UserA.LastName1
Year Created: 2012 2014
I'm trying to output like this:
User Name: UserB LastName1
Login Name: UserB.LastName1
Year Created: 2012
User Name: UserA LastName1
Login Name: UserA.LastName1
Year Created: 2014
The script I'm using is as follows:
$UserName = read-host "Please Enter Users LastName"
$SAN = "*$UserName*"
$GetUser = GET-ADUSER -Filter {(SamAccountName -like $SAN) -and (enabled -ne "FALSE")}
-Properties * | Sort-Object givenname -Descending
foreach ($FoundUser in $GetUser)
{
write-host "User Name: " $GetUser.CN
write-host "Login Name: " $GetUser.samaccountname
write-host "Year Created: " $getUser.whencreated.year
write-host
}
$GetUser.CN results in the following, so I'm trying to figure out why my write-host is producing two entries per line.
UserB LastName1
UserA LastName1
Upvotes: 0
Views: 10024
Reputation: 17342
In your foreach
loop, you need to replace each $GetUser
with $FoundUser
. $GetUser
Contains the whole list, while $FoundUser
is the current list entry, which changes with each iteration of the loop. The way you currently have it implemented, you print the full contents of the list each iteration rather than printing only the current item.
Your updated code will look like this:
$UserName = read-host "Please Enter Users LastName"
$SAN = "*$UserName*"
$GetUser = GET-ADUSER -Filter {(SamAccountName -like $SAN) -and (enabled -ne "FALSE")}
-Properties * | Sort-Object givenname -Descending
foreach ($FoundUser in $GetUser)
{
write-host "User Name: " $FoundUser.CN
write-host "Login Name: " $FoundUser.samaccountname
write-host "Year Created: " $FoundUser.whencreated.year
write-host
}
Upvotes: 2