powershell返回Get-ADComputer:对象名称语法错误



我想获得特定OU中的所有计算机并ping它们,但是我在get - adcomputer中遇到麻烦。

代码:

# Enter CSV file location
$csv = "filepath.csv"
# Add the target OU in the SearchBase parameter
$Computers = Get-ADComputer -Filter * -SearchBase "OU=Servers,DC=mydomain,DC=com" | Select Name | Sort-Object Name
$Computers = $Computers.Name
$Headers = "ComputerName,IP Address"
$Headers | Out-File -FilePath $csv -Encoding UTF8
foreach ($computer in $Computers)
{
Write-host "Pinging $Computer"
$Test = Test-Connection -ComputerName $computer -Count 1 -ErrorAction SilentlyContinue -ErrorVariable Err
if ($test -ne $null)
{
$IP = $Test.IPV4Address.IPAddressToString
$Output = "$Computer,$IP"
$Output | Out-File -FilePath $csv -Encoding UTF8 -Append
}
Else
{
$Output = "$Computer,$Err"
$output | Out-File -FilePath $csv -Encoding UTF8 -Append
}
cls
}

和我得到:

Get-ADComputer : The object name has bad syntax
At script.ps1:2 char 14
+ ... omputers = Get-ADComputer -Filter * -SearchBase "OU=Servers, ...
+                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+CategoryInfo          : NotSpecified: (:) [Get-ADComputer], ADException
+FullyQualifiedErrorId : ActiveDirectoryServer:8335,Microsoft,ActiveDirectory,Management,Command.GetADComputer

p。这段代码取自这里。是的,我知道我不应该这样做,但在得到这个错误之后一次又一次,我想尝试一个有效的代码。

再次检查您用作搜索基的OU是否正确。当它处于关闭状态时会发生此错误。

除此之外,我建议使用System.Net.NetworkInformation.Ping类。它比Test-Connection快得多,因为你对ping超时有更多的控制。

$ping = New-Object System.Net.NetworkInformation.Ping
$pingTimeutMS = 200
$computers = Get-ADComputer -Filter * -SearchBase "OU=Servers,DC=mydomain,DC=com" 
$results = $computers | Sort-Object Name | ForEach-Object {
$ComputerName = $_.Name
Write-Host "Pinging $ComputerName..."
$test = $ping.Send($ComputerName, $pingTimeutMS)
[pscustomobject]@{
"Computer" = $ComputerName
"IP Address" = if ($test.Status -eq "Success") { $test.Address } else { $test.Status }
}
}
$results | Export-Csv "filepath.csv" -Delimiter ',' -NoTypeInformation -Encoding UTF8

不将行附加到CSV中也感觉不那么笨拙。

相关内容

  • 没有找到相关文章

最新更新