我尝试使用powershell 3查找AD并检查我的csv中的用户(sAMAccountName)是否在AD中存在并处于活动状态。但是我可能会从一个错误跳到另一个错误,可能是基于括号和括号,但我找不到正确的方法。我尝试了不同的过滤器,尝试将它们传递给变量,但我最终得到了"找不到匹配参数名称-eq ..."的参数。看起来错误发生在Get-ADUser,因为$ adsearch未设置,因此无法评估if($ adsearch)。
csv文件已清理(前导空格等)并且看起来像(只有一列带有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
}
}
解决。
作为参考,我将上面的错误脚本留下,这是工作脚本(感谢Tomer和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
}
}
答案 0 :(得分:1)
对于您显示的CSV文件,当我添加标题行SAMAccountName
时,以下内容适用于我:
$username = $user.SAMAccountName
$adsearch = Get-AdUser -Filter {(samAccountName -eq $username) -and (Enabled -eq $true)}
注意大括号而不是引号。