Mohammad Nadeem
Mohammad Nadeem

Reputation: 9392

Add item to Select-Object or Format-Table

I have below powershell script which returns me the list of services running from a specific account on different servers:

$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
}

And this returns me results like:

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

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

Now I would like to add the name of the server in the list as well and get results displayed something like:

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

Upvotes: 1

Views: 1646

Answers (3)

vonPryz
vonPryz

Reputation: 24071

The WMI class Win32_Service already contains server's name, so just pick it from PSComputerName member like so,

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

Upvotes: 2

David Martin
David Martin

Reputation: 12248

You can extend what's being returned by using Select-Object as follows:

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

You should remove Write-Host so as not to interfere with the results:

$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
}

Upvotes: 2

CB.
CB.

Reputation: 60910

try this way:

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

Upvotes: 1

Related Questions