Reputation: 11
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
Upvotes: 1
Views: 364
Reputation: 4301
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
}
Upvotes: 1