small problem

Hi All,

i have a small problem
simple script to find computer in AD

### Get-ADComputer by Name ###
### C:\Users.txt - user names

$username = Get-Content "C:\Users.txt"
foreach ($user in $username)
{
Get-ADComputer -Filter $("Description -like '*$user*'") -Property Name,Description,OperatingSystem | Select Name,Description,OperatingSystem | 
Export-Csv "C:\Users.csv" -Append -NoTypeInformation
}

this part working Ok, just one things
if it didn’t find description in AD it will remove it from list
My question, how i can have the same list in scv and if its can’t find in AD it will say not in AD

Thanks

This could be a starting point for you:

$username = Get-Content “C:\Users.txt”
foreach ($user in $username)
{
$SearchHit = Get-ADComputer -Filter $(“Description -like ‘$user’”) -Property Name,Description,OperatingSystem
If($SearchHit){
$output=[PSCustomObject]@{
‘Name’ = $SearchHit.Name
‘Description’ = $SearchHit.Description
‘OperatingSystem’ = $SearchHit.OperatingSystem
}
}
Else{
$output=[PSCustomObject]@{
‘Name’ = $user
‘Description’ = ‘Not in AD’
‘OperatingSystem’ = ‘Not in AD’
}
}
$output |
Export-Csv “C:\Users.csv” -Append -NoTypeInformation
}

(untested!!)

Hi Olaf,

Thank you, this is what i was looking for
one more things, if in list i have name like O’laf or B’rad it throwing error
how to avoid this

Thanks

Change

“Description -like ‘$user’”
to
“Description -like “”$user”“”

Thank you Olaf

why its not working in ADUser, i try modify your script
to


$username = Get-Content “C:\Users.txt”

foreach ($user in $username)
{

$SearchHit = Get-ADUser -Filter (“cn -Like ‘$user’”) -Property Name,SamAccountName,mail
If($SearchHit){
$output=[PSCustomObject]@{
‘Name’ = $SearchHit.Name
‘SamAccountName’ = $SearchHit.SamAccountName
‘Mail’ = $SearchHit.mail
}
}
Else{
$output=[PSCustomObject]@{
‘Name’ = $user
‘SamAccountName’ = ‘Not in AD’
‘Mail’ = ‘Not in AD’
}
}
$output |
Export-Csv “C:\Users.csv” -NoTypeInformation
}


but its not working this way

Thanks again for your help

Do you get errors? I already have a suspision … :wink:

No, no error
in csv file just one last name from the list

i just removed from code -Append

OK … try to change

-Filter (“cn -Like ‘$user’”)
to
-Filter $(“cn -like “”$user”“”)

Hi Olaf,
still not working
no errors but it in output file just last name from list

So you have to add the “-append” again. Otherwise every new entry will overwrite the last one.

Thank you :wink: