Alex
Alex

Reputation: 18556

How to use Powershell splatting for Azure CLI

I want to use Powershell splatting to conditionally control which parameters are used for some Azure CLI calls. Specifically for creating CosmosDb collections.

The target was something like this:

$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

Unfortunately, this only works for db-name and collection-name. The other parameters fail with this error:

az : ERROR: az: error: unrecognized arguments: --url-connection:https://myaccount.documents.azure.com:443 
--key:secretKey

Upvotes: 5

Views: 1572

Answers (1)

Alex
Alex

Reputation: 18556

After some back and forth, I ended up using array splatting:

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

az cosmosdb collection create @params 

Now I can do things like this:

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
}

Upvotes: 12

Related Questions