当我从Tim Rhymer运行此脚本时,我的某些域控制器出现错误,服务器由于某种原因超时 . 当我收到下面的错误时,它会使脚本停止15-30秒,而不是域控制器的查询需要1-2秒 . 如何捕获错误并且不会拖延脚本这么久?以下是该部分
错误信息:
Get-ADObject : Unable to contact the server. This may be because this server
does not exist, it is currently down, or it does not have the Active Directory
Web Services running.
At C:\Users\jimbob\AD_Lookup.ps1:58 char:54
+ ... countName | Get-ADObject -Server $hostname -Properties lastlogon
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ResourceUnavailable: (CN=jimbob...DC=domaincontroller,DC=com:User) [Get-ADObject], ADServerDownException
+ FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.GetADObject
下面是查询域控制器以从所有域控制器获取lastlogon日期的脚本 .
Import-Module ActiveDirectory
function Get-ADUsersLastLogon() {
$dcs = Get-ADDomainController -Filter {Name -like "*"}
$users = Get-ADUser -Filter *
$time = 0
$exportFilePath = "c:lastLogon.csv"
$columns = "name,username,datetime"
Out-File -FilePath $exportFilePath -Force -InputObject $columns
foreach ($user in $users) {
foreach ($dc in $dcs) {
$hostname = $dc.HostName
$currentUser = Get-ADUser $user.SamAccountName | Get-ADObject -Server $hostname -Properties lastLogon
if ($currentUser.LastLogon -gt $time) {
$time = $currentUser.LastLogon
}
}
$dt = [DateTime]::FromFileTime($time)
$row = $user.Name + "," + $user.SamAccountName + "," + $dt
Out-File -FilePath $exportFilePath -Append -NoClobber -InputObject $row
$time = 0
}
}
Get-ADUsersLastLogon
我想我需要更改一些东西以捕获错误或绕过导致该脚本的以下部分之一的错误的问题:
$dcs = Get-ADDomainController -Filter {Name -like "*"}
要么
$currentUser = Get-ADUser $user.SamAccountName |
Get-ADObject -Server $hostname -Properties lastLogon