【问题标题】:PowerShell - iterating over computer names in Active DirectoryPowerShell - 迭代 Active Directory 中的计算机名称
【发布时间】:2015-07-23 20:48:39
【问题描述】:

我是 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-#### 部分之外,我最好的方法是什么?

【问题讨论】:

    标签: powershell active-directory powershell-4.0


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-06-28
      • 1970-01-01
      • 2016-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-18
      • 1970-01-01
      相关资源
      最近更新 更多