PowerShell - 迭代Active Directory中的计算机名称

时间:2015-07-23 20:48:40

标签: powershell active-directory powershell-v4.0

我是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的每个迭代以包含标题行。

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

Name                                                                                                                                                                                          
----                                                                                                                                                                                          
PC-0649

在这种情况下,剥离PC以外的所有内容的最佳方式是什么?####部分?

1 个答案:

答案 0 :(得分:1)

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

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