我正在执行Powershell脚本以在每个AD域控制器上获取badpwdcount。大约有50个域控制器。运行脚本时,无法访问其中一台服务器。该脚本应记录失败的连接尝试并继续。但是,该脚本将在尝试失败的连接后终止。
Param(
$BadOption,
$Samaccountname = "<accountname>"
)
Import-Module ActiveDirectory
$result = @()
try {
$DC = Get-ADDomainController -Filter * | select -exp hostname
$DC1 = $DC -notlike { "<DC Server>", "<DC Server1>" } # skipping few
foreach ($Domaincontroller in $DC1) {
$count = Get-ADUser -Identity $Samaccountname -Server $Domaincontroller -Properties badPwdCount | select badPwdCount
$result += $Domaincontroller + ',' + $count
}
#echo $result
}
catch {
$errmsg = $_.Exception.Message
$result += $Domaincontroller + ' :' + "Error : " + $errmsg
}
return $result
答案 0 :(得分:1)
Continue
语句应允许您在Try-Catch
块中终止错误之后继续进行处理。
$result = @()
$DC = Get-ADDomainController -Filter * | select -exp hostname
$DC1 = $DC -notlike {"<DC Server>","<DC Server1>"} # skipping few
foreach($Domaincontroller in $DC1)
{
try
{
$count = Get-ADUser -Identity $Samaccountname -Server $Domaincontroller -Properties badPwdCount | select badPwdCount
$result += $Domaincontroller + ',' + $count
}
catch {
$errmsg = $_.Exception.Message
$result += $Domaincontroller + ' :'+ "Error : "+$errmsg
Continue
}
}
$result
答案 1 :(得分:1)
就像这样:
$result = @()
$DC = Get-ADDomainController -Filter * | select -exp hostname
$DC1 = $DC -notlike {"<DC Server>","<DC Server1>"} # skipping few
ForEach($Domaincontroller in $DC1) {
Write-Host $Domaincontroller
Try {
$count = Get-ADUser -Identity $Samaccountname -Server $Domaincontroller -Properties badPwdCount | select badPwdCount
$result += $Domaincontroller + ',' + $count
}
Catch{
$errmsg = $_.Exception.Message
$result += $Domaincontroller + ' :'+ "Error : "+$errmsg
}
}
Return $result
答案 2 :(得分:1)
为什么不在循环中添加测试以检查是否可以访问domaincontroller?
# An array of DC hostnames you want to exclude
$Exclude = "<DC Server>","<DC Server1>"
# By setting $ErrorActionPreference to Stop, PowerShell treats all non-terminating errors as terminating.
# This is useful when using try{..} catch{..} blocks.
$oldErrorAction = $ErrorActionPreference
$ErrorActionPreference = 'Stop'
$result = @()
$DC = Get-ADDomainController -Filter * | Select-Object -ExpandProperty hostname | Where-Object { $Exclude -notcontains $_ }
foreach($Domaincontroller in $DC) {
if (Test-Connection -ComputerName $Domaincontroller -Count 1 -Quiet) {
try {
$count = (Get-ADUser -Identity $Samaccountname -Server $Domaincontroller -Properties badPwdCount).badPwdCount
$result += "$Domaincontroller, $count"
}
catch {
$errmsg = $_.Exception.Message
$result += "$Domaincontroller :Error : $errmsg"
}
}
else {
$result += "$Domaincontroller :Error : Failed connection attempt"
}
}
# Restore the previous value for the $ErrorActionPreference variable
$ErrorActionPreference = $oldErrorAction
$result