0
votes

Powershell novice here. Trying to find out why the $_ value can't be used in my expression:

$ServerList = @(
'Server1',
'Server2',
'Server3'
)

$ServerList | ForEach-Object (get-cswindowsservice -Name "rtcpdpcore" -Computer $_ | Select-object @{Label = "ServerName";Expression={$_}}, Status, Displayname | format-table -autosize -wrap)

Getting error: Get-CsWindowsService : Cannot validate argument on parameter 'ComputerName'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.

But THIS does output the array values fine??

$ServerList = @(
'Server1',
'Server2',
'Server3'
)

$ServerList | ForEach-Object {write-output $_}

Why is '$_' null in the first example? But populated in the second?

Thanks

1
You are using wrong kind of parenthesis for the 1st example. It should be {} instead of (). - zett42
Thank You! So simple! That's working. - Oliver Woodall
New problem now. The value being passed to my label 'ServerName', is "rtcpdpcore" and not the Array Value. Very odd. - Oliver Woodall
New problem, new question. - Walter Mitty
WaitingForGuacamole - Nailed it. Thanks so much. - Oliver Woodall

1 Answers

1
votes

Having changed your brackets from () to {}, the problem you're having is that the scope of $_ changes as it works through the pipeline, so $_ on the Select-Object is the object that was passed by Get-CSWindowsService, not the ForEach-Object. Try a minor refactor:

$ServerList | `
  ForEach-Object {
    $serverName = $_
    Get-CSWindowsservice -Name "rtcpdpcore" -Computer $serverName | `
    Select-object @{Label = "ServerName";Expression={$serverName}}, Status, Displayname | `
    Format-Table -autosize -wrap
  }