簡體   English   中英

Powershell - 將數組值作為參數傳遞

[英]Powershell - Passing Array Value as a Parameter

Powershell新手這里。 試圖找出為什么不能在我的表達式中使用 $_ 值:

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

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

出現錯誤:Get-CsWindowsService:無法驗證參數“ComputerName”上的參數。 參數為 null 或為空。 提供一個不是 null 或空的參數,然后重試該命令。

但是這對 output 的數組值好嗎?

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

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

為什么在第一個示例中是 '$_' null ? 但在第二個填充?

謝謝

將括號從()更改為{}后,您遇到的問題是$_的 scope 在通過管道時會發生變化,因此Select-Object上的$_Get-CSWindowsService ,而不是ForEach-Object 嘗試一個小的重構:

$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