PowerShell 展開與雜湊表值

最後更新: 2021-12-04 17:34:29 +0800 +0800
原文以英文撰寫。您正在閱讀AI翻譯版本。

PowerShell 展開可以將雜湊表或陣列作為具名引數或位置引數傳遞。 它可以避免重複撰寫冗長的參數清單,並將組態與命令呼叫分離。

展開 PowerShell 命令 #

在呼叫位置為雜湊表變數加上 @ 前綴:

powershell
$request = @{
    Uri         = 'https://api.example.test/items'
    Method      = 'Get'
    Headers     = @{ Accept = 'application/json' }
    TimeoutSec  = 30
}

Invoke-RestMethod @request

雜湊表索引鍵必須符合參數名稱,包括受支援的別名。展開不會將任意字串展開為 shell 語法;PowerShell 會將產生的值繫結為具型別的命令引數。

PowerShell 7.1 及更新版本允許明確寫出的具名參數覆寫展開雜湊表中的相同參數。較早版本的 PowerShell 會改為回報重複繫結,因此跨版本指令碼應在呼叫前更新複製的雜湊表:

powershell
$effective = $request.Clone()
$effective.TimeoutSec = 60
Invoke-RestMethod @effective

陣列提供位置引數展開:

powershell
$copyArgs = @('source.txt', 'destination.txt')
Copy-Item @copyArgs

外部程式與插值 #

原生可執行檔接收的是字串,而不是 PowerShell 參數繫結。插值字串中的雜湊表屬性需要使用子運算式:

powershell
$config = @{
    AppId     = 'example-id'
    GroupCode = 'workers'
}

& $connector `
    "--app-id=$($config.AppId)" `
    "--group-code=$($config.GroupCode)"

"--app-id=$config.AppId" 會展開 $config,並將 .AppId 保留為字面文字,因此產生的值會以雜湊表的字串表示開頭。$($config.AppId) 會在插值前評估成員存取。

當可執行檔具有選用旗標時,請建構引數陣列:

powershell
$arguments = @(
    '--server-mode=http'
    '--threads=10'
    "--app-id=$($config.AppId)"
)

& $connector @arguments
if ($LASTEXITCODE -ne 0) {
    throw "Connector failed with exit code $LASTEXITCODE"
}

呼叫運算子後的陣列展開會為陣列中的每個元素提供一個引數。避免建構單一命令字串並將其傳遞給 Invoke-Expression;引數陣列可以保留邊界,並避免額外的剖析步驟。

在 Windows 上,PowerShell 7.3 透過 $PSNativeCommandArgumentPassing 變更了原生引數傳遞方式;Standard、Windows 和 Legacy 模式控制引擎建構原生命令列的方式。類 Unix 系統會傳遞引數向量,而 Windows 程式可能套用自己的命令列剖析器。請針對支援的 PowerShell 和可執行檔版本測試空字串、內嵌引號和結尾反斜線,而不要手動序列化命令。

評論

在 GitHub 上閱讀或評論(發表評論需要登入)