有了所有这些评论和已经给出的不完整答案,我担心 OP 会更加困惑......
为了让OP更好地理解,我尽可能地坚持他的原始代码。
首先:
我假设通过查看代码,输入的 csv 文件看起来与此类似
"FirstName","LastName","Employee"
"Elvis","Presley","12345"
"Axl","Rose","987654"
"Janis","Joplin","654283"
我在这里看到的主要问题是代码正在使用 EmployeeID 属性(字符串)搜索 AD 用户。通过使用过滤器,eq
在 AD 中找到的字符串必须与 csv 中的字符串完全相同(尽管不区分大小写)。如果不是这种情况,代码将无法通过 using 找到用户,-eq
但也许通过比较 CSV 和 AD 中的内容,可以使用不同的运算符,例如-like
. 那是让OP弄清楚。
接下来是代码:
#Script Starts
$Users = Import-Csv "\folder\Test.csv"
Import-Module ActiveDirectory
$path = Split-Path -parent ".\folder\*.*"
# Create log date
$logdate = Get-Date -Format yyyy-MM-dd-THH.mm.ss
$logfile = $path + "\logs\$logdate.logfile.txt"
# while you're at it, create the full path and filename for the output csv
$outFile = Join-Path $path $($logdate + ".ADEnabled-Disabled.csv")
# create an array for the output file
# You CAN do without by letting PowerShell do the aggregating of objects for you
# but in this case I think it will make things more readable to collect ourselves.
$result = @()
ForEach ($User In $Users) {
# Find the user by the 'Employee' field in the csv and return an object with the required properties
# Use -LDAPFilter which requires the LDAP syntax: "(employeeID=$($User.Employee))"
# Or use -Filter where you use the Powershell syntax
$adUser = Get-ADUser -Filter "EmployeeID -eq $($User.Employee)" -Properties DisplayName, Enabled, EmployeeID |
Select-Object DisplayName, Enabled, EmployeeID
if ($adUser) {
# if the above statement did find the user, we add this to the result array
$result += $adUser
}
else {
$msg = "User '{0} {1}' not found. Check the Employee id {2}." -f $user.FirstName, $user.LastName, $user.Employee
Write-Warning $msg
Add-content $logfile -Value $msg
}
}
# now write the output csv as a new file. Because it has a complete date and time in the name
# the chances of overwriting an existing file are very slim indeed, but we'll use -Force anyway.
$result | Export-Csv -Path $outFile -NoTypeInformation -Force
#Finish
希望这可以帮助