Reputation: 1
I try to lookup AD with powershell 3 and check if users (sAMAccountName) in my csv are existing and active in AD. However I am hopping from one error to the next one probably based on brackets and parenthesis but I do not find the correct way. I tried different filters, tried to pass them through a variable but I end up with "a parameter cannot be found that matches parameter name -eq...". It looks like the error is at Get-ADUser as $adsearch is not set therefore fails to evaluate if($adsearch).
the csv file is sanitized (leading spaces etc.) and looks like (only one column with SAMAccountName):
john.doe
jane.doe
doej2
foo.bar
barf5
param ($inputfile='.\users.csv',$logfile='.\log.csv')
$csv = Import-CSV $inputfile
#"samAccountName,Search Result" | Add-Content $logfile
ForEach ($user in $csv){
echo $user;
#$adsearch = Get-ADUser -Filter 'sAMAccountName -eq "$($user)" -and Enabled -eq $true'
#$filter = "sAMAccountName -eq $($user) -and Enabled -eq $($true)"
#Write-Host "Filter is $filter"
$adsearch = Get-ADUser -Filter "(sAMAccountName -eq '$($user)') -and (Enabled -eq '$($true)')"
echo $adsearch
if ($adsearch){
echo "Found";
echo "$error"
#"$user, Found" | Add-Content $logfile
}
else{
echo "NOT FOUND";
echo "$error"
#"$user, Not Found" | Add-Content $logfile
}
}
Solved.
For reference I leave the buggy script above, here is the working script (thanks Tomer and Charlie Joynt):
param ($inputfile='.\users.csv',$logfile='.\log.csv')
$csv = Import-CSV $inputfile
"samAccountName,Search Result,Error" | Add-Content $logfile
ForEach ($user in $csv){
$username = $user.SAMAccountName;
$adsearch = Get-ADUser -Filter {(samAccountName -eq $username) -and (Enabled -eq $true)}
echo "search for active user $user"
if ($adsearch){
echo "Found";
"$user, Found" | Add-Content $logfile
}
else{
echo "NOT FOUND";
"$user, Not Found, $error" | Add-Content $logfile
}
}
Upvotes: 0
Views: 6290
Reputation: 1704
For the CSV file you showed, when I add a header line SAMAccountName
, the following works for me:
$username = $user.SAMAccountName
$adsearch = Get-AdUser -Filter {(samAccountName -eq $username) -and (Enabled -eq $true)}
Notice the curly brackets instead of the quote marks.
Upvotes: 1