简体   繁体   English

Powershell - 将数组值作为参数传递

[英]Powershell - Passing Array Value as a Parameter

Powershell novice here. Powershell新手这里。 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'.出现错误:Get-CsWindowsService:无法验证参数“ComputerName”上的参数。 The argument is null or empty.参数为 null 或为空。 Provide an argument that is not null or empty, and then try the command again.提供一个不是 null 或空的参数,然后重试该命令。

But THIS does output the array values fine??但是这对 output 的数组值好吗?

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

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

Why is '$_' null in the first example?为什么在第一个示例中是 '$_' null ? But populated in the second?但在第二个填充?

Thanks谢谢

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 .将括号从()更改为{}后,您遇到的问题是$_的 scope 在通过管道时会发生变化,因此Select-Object上的$_Get-CSWindowsService ,而不是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
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM