Get-ADComputer |获取进程

时间:2017-05-17 10:04:18

标签: powershell

当我运行时:

Get-Process -name csrss -ComputerName (
    Get-AdComputer -Filter {
        (name -eq "gate") -or (name -eq "client")
    } | Select-Object -ExpandProperty name
) | Select-Object Name,MachineName

Get-Process -name csrss -ComputerName gate,client | Select-Object Name,MachineName

我从两台计算机中选择了一些进程:

Name                                MachineName                
----                                ----------- 
csrss                               CLIENT
csrss                               GATE 
csrss                               CLIENT                 
csrss                               GATE 

但是当我跑这个时:

Get-AdComputer -Filter {(name -eq "gate") -or (name -eq "client")} |
Select-Object @{Name='computername';Expression={$_.name}} |
Get-Process -name csrss | 
Select-Object name,machinename

我得到了这个输出:

Name                                MachineName                
----                                ----------- 
csrss                               GATE                
csrss                               GATE 

如果我将名称client更改为DC(它是本地主机),则仅显示来自DC的进程。我键入计算机名称(首先是GATE或首先是DC)并不重要。

即使我输入了这个:

Get-AdComputer -Filter * |
Select-Object @{Name='computername';Expression={$_.name}} |
Get-Process -name csrss |
Select-Object name,machinename

我只从一台机器(DC = localhost)获得输出:

Name                                MachineName                
----                                ----------- 
csrss                               DC                
csrss                               DC 

为什么会这样?为什么我只从一台机器上获取进程?

我无法获得逻辑,Get-Process在第三种情况下获得ComputerName的方式。

1 个答案:

答案 0 :(得分:1)

您遇到了困难,因为Get-ADComputer正在返回两个对象,而不是一个具有computername的两个值数组的对象。以下是四种情况来说明差异:

# One Object, two value property
[pscustomobject]@{computername="GATE","CLIENT"} |
    Get-Process csrss

# Two Objects, one value property
[pscustomobject]@{computername="GATE"},[pscustomobject]@{computername="CLIENT"} |
    Get-Process csrss

# Two Objects, one value property using a ForEach-Object
[pscustomobject]@{computername="GATE"},[pscustomobject]@{computername="CLIENT"} |
    ForEach-Object { Get-Process csrss -Computername $_.Computername}

# Two Objects, one value property using a ForEach-Object with a nested pipe
[pscustomobject]@{computername="GATE"},[pscustomobject]@{computername="CLIENT"} |
    ForEach-Object { $_ | Get-Process csrss}

将此概念应用于您的代码将如下所示:

Get-AdComputer -Filter {(name -eq "gate") -or (name -eq "client")} |
    Select-Object @{Name='computername';Expression={$_.name}} | 
    ForEachObject {
        Get-Process -name csrss -Computername $_.Computername | 
        Select-Object name,machinename
    }

或者使用ForEach-Object中的管道

Get-AdComputer -Filter {(name -eq "gate") -or (name -eq "client")} |
    Select-Object @{Name='computername';Expression={$_.name}} | 
    ForEachObject { $_ |
        Get-Process -name csrss | 
        Select-Object name,machinename
    }