下面的脚本包含一个带有列samaccountname
的CSV输入和一个用户列表。运行时,它会生成一个包含3列的CSV报告:
如果以其当前状态运行,它确实会生成一个关于帐户是否被禁用以及是否存在的报告,但是如果它遇到AD中不存在的用户,则它们不会添加到CSV报告和以下内容中抛出每个用户的错误:
无法索引到空数组。在行:4 char:75 + ...($ account =([adsisearcher]"(samaccountname = $($ _。samaccountname))")。fin ... + ~~~~~~~~~~~~~~~~~ + CategoryInfo:InvalidOperation:(:) [],RuntimeException + FullyQualifiedErrorId:NullArray
是否可以将不存在的用户添加到存在的列帐户下的CSV报告中,其值为FALSE
Import-CSV C:\ScriptRepository\Users.csv | ForEach-Object {
New-Object -TypeName PSCustomObject -Property @{
samaccountname = $_.samaccountname
AccountExists = [bool]($account=([adsisearcher]"(samaccountname=$($_.samaccountname))").findone()).count
AccountDisabled = [bool]($account.properties.useraccountcontrol[0] -band 2)
}
} | Export-Csv C:\ScriptRepository\UsersState.csv -NoTypeInformation
答案 0 :(得分:1)
以下是我如何处理它:
$ADS_UF_ACCOUNTDISABLE = 2
$searcher = [ADSISearcher] ""
$searcher.PropertiesToLoad.AddRange(@("userAccountControl"))
Import-Csv "Users.csv" | ForEach-Object {
$searcher.Filter = "(sAMAccountName=$($_.sAMAccountName))"
$account = $searcher.FindOne()
if ( $account ) {
$exists = $true
$disabled = ($account.Properties["useraccountcontrol"][0] -band $ADS_UF_ACCOUNTDISABLE) -ne 0
}
else {
$exists = $false
$disabled = "N/A"
}
[PSCustomObject] @{
"sAMAccountName" = $_.sAMAccountName
"AccountExists" = $exists
"AccountDisabled" = $disabled
}
}
答案 1 :(得分:0)
您可以通过将逻辑移到哈希表之前来完成此操作:
Import-CSV C:\ScriptRepository\Users.csv | ForEach-Object {
$AccountExists = If ( (([adsisearcher]"(samaccountname=$($_.samaccountname))").FindOne()) ) { $true } else { $false }
If ($AccountExists) { $AccountDisabled = [bool]($AccountExists.properties.useraccountcontrol[0] -band 2) } Else { $AccountDisabled = '' }
New-Object -TypeName PSCustomObject -Property @{
samaccountname = $_.samaccountname
AccountExists = $AccountExists
AccountDisabled = $AccountDisabled
}
} | Export-Csv C:\ScriptRepository\UsersState.csv -NoTypeInformation