PowerShell - 遍历 Active Directory 中的计算机名称

PowerShell - iterating over computer names in Active Directory

我是 PowerShell 的新手,我正在尝试编写一个脚本来查询 AD 的机器名称,检查哪些机器正在响应并将输出写入文件。到目前为止我有这个:

$computers = Get-ADComputer -filter {(Name -like "PC*")} | Select-Object -Property Name
foreach ($computer in $computers) {
    if((Test-Connection -Cn $computer -BufferSize 16 -Count 1 -Ea 0 -Quiet)) {
        "Machine $computer connected." | Out-File "out.txt" -Append
    } else {
        "Machine $computer not connected." | Out-File "out.txt" -Append
    } #end if
} #end foreach

我在输出文本文件中得到的内容如下所示:

...
Machine @{Name=PC-0649} not connected.
Machine @{Name=PC-1541} not connected.
Machine @{Name=PC-1574} not connected.
...

我认为我的问题在于第一行的 Select-Object -Property Name 部分。 运行 调试器,看起来 PowerShell 正在格式化 $computer 的每次迭代以包含 header 行。

[DBG]: PS Y:\>> $computer

Name                                                                                                                                                                                          
----                                                                                                                                                                                          
PC-0649

在这种情况下,什么是去除 PC-#### 部分以外的所有内容的最佳方法?

我认为您的问题是您在 $computers 中仍然有一个(截断的)计算机对象列表。通过 $computers[0].GetType() 验证这一点。如果您没有看到 String,则它不是字符串。 :) 试试这个:

$computers = Get-ADComputer -filter {(Name -like "PC*")} | 
   Select-Object -ExpandProperty Name