如何为 Azure CLI 使用 Powershell splatting

Ale*_*AIT 3 powershell azure azure-cli

我想使用Powershell splatting有条件地控制用于某些 Azure CLI 调用的参数。专门用于创建 CosmosDb 集合。

目标是这样的:

$params = @{
    "db-name" = "test";
    "collection-name"= "test2";
    # makes no difference if I prefix with '-' or '--'
    "-key" = "secretKey";
    "url-connection" = "https://myaccount.documents.azure.com:443"
    "-url-connection" = "https://myaccount.documents.azure.com:443"
}

az cosmosdb collection create @params
Run Code Online (Sandbox Code Playgroud)

不幸的是,这只适用于db-namecollection-name。其他参数失败并显示此错误:

az : ERROR: az: error: unrecognized arguments: --url-connection:https://myaccount.documents.azure.com:443 
--key:secretKey
Run Code Online (Sandbox Code Playgroud)

Ale*_*AIT 9

经过一番来回,我最终使用了数组 splatting

$params = "--db-name", "test", "--collection-name", "test2", 
    "--key", "secretKey",
    "--url-connection", "https://myaccount.documents.azure.com:443"

az cosmosdb collection create @params 
Run Code Online (Sandbox Code Playgroud)

现在我可以做这样的事情:

if ($collectionExists) {
    az cosmosdb collection update @colParams @colCreateUpdateParams
} else {
    # note that the partition key cannot be changed by update
    if ($partitionKey -ne $null) {
        $colCreateUpdateParams += "--partition-key-path", $partitionKey
    }
    az cosmosdb collection create @colParams @colCreateUpdateParams
}
Run Code Online (Sandbox Code Playgroud)