将项添加到Select-Object或Format-Table

时间:2014-06-04 10:09:07

标签: powershell powershell-v2.0

我有以下powershell脚本,它返回从不同服务器上的特定帐户运行的服务列表:

$servers = @(
    "Server1",
    "Server2"       
)

foreach($server in $servers)
{
    Write-Host $server      
    Get-WMIObject Win32_Service -ComputerName $server | Where-Object{$_.StartName -eq 'serviceaccount'} | Sort-Object -Property StartName | Format-Table Name, StartName
}

这会给我带来如下结果:

Server1
Name                                          StartName                                     
----                                          ---------
AdobeARMservice                               serviceaccount
PlugPlay                                      serviceaccount

Server2
Name                                          StartName                                     
----                                          ---------
UxSms                                         serviceaccount

现在我想在列表中添加服务器的名称,并显示如下结果:

Name                StartName              Server
----                ---------              -------
AdobeARMservice     serviceaccount         Server1
PlugPlay            serviceaccount         Server1
UxSms               serviceaccount         Server2

3 个答案:

答案 0 :(得分:2)

您可以使用Select-Object扩展返回的内容,如下所示:

select-object Name, StartName, @{Name='Server';Expression={$server}}

您应该删除Write-Host,以免干扰结果:

$servers = @(
    "Server1",
    "Server2"       
)

foreach($server in $servers)
{
    Get-WMIObject Win32_Service -ComputerName $server | `
        Where-Object{$_.StartName -eq 'serviceaccount'} | ` 
        select-object Name, StartName, @{Name='Server';Expression={$server}} | `
        Sort-Object -Property StartName | `
        Format-Table Name, StartName, Server
}

答案 1 :(得分:2)

WMI类Win32_Service已经包含服务器的名称,所以只需从PSComputerName成员中选择它,

foreach($server in $servers){
    gwmi Win32_Service -ComputerName $server | % {$_.StartName -eq '...'} |`
    sort -Property StartName | ft Name, StartName, PSComputerName
}

答案 2 :(得分:1)

尝试这种方式:

... | Format-Table Name, StartName, @{n="Server";e={$server}}