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

powershell returning Get-ADComputer : The object name has bad syntax

我想获取特定 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

ps。此代码取自 here。是的,我知道我不应该那样做,但是在收到这个错误之后 一次又一次,我想尝试一个有效的代码。

仔细检查您用作搜索基础的 OU 是否正确。关闭时出现此错误。

除此之外,我建议使用 the System.Net.NetworkInformation.Ping class。它比 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 中也感觉不那么笨拙。