I am trying to build a command using different strings that are created conditionally. This command is for adding a key to vault.
Thing is, either in key description or value double ampersands can occur.
I managed to escape single ampersand, but not the two or more.
Current code, excluding parameter passing etc for brevity:
[string]$params = "az keyvault secret set --name `'$name`' --vault-name `'$destinationVault`' "
if($description -ne '')
{
# Escaping ampersand so that it can be used in Invoke-Expression
$params += "--description `'$($description -replace '&', '"&"')`' "
}
$params += "--disabled $(if($enabled) { "false" } else { "true" }) "
if($expires -ne '')
{
$params += "--expires `'$(([DateTime]($expires)).ToUniversalTime().ToString($dateFormat))`' "
}
if($notBefore -ne '')
{
$params += "--not-before `'$(([DateTime]($notBefore)).ToUniversalTime().ToString($dateFormat))`' "
}
if($tags -ne '')
{
$params += "--tags `'$tags`' "
}
else
{
$params += "--tags `"`" "
}
$params += "--value `'$($value -replace '&', '"&"')`'"
return $params
Returned params
is used by parent script - $result = Invoke-Expression (Build-SetSecretCommand $secret $destinationKeyVault)
Result of this code ran on example data with single &
in secret value in console looks like that:
az keyvault secret set --name 'secret_name' --vault-name 'vault_name' --disabled false --tags 'file-encoding=utf-8' --value 'super_secret://+_with_symbols"&"ampersand!'
and translates to super_secret://+_with_symbols&ersand!
in created secret value.
As mentioned, code works with single &
, but if there are more than one symbols like that, I am getting errors like
Invoke-Expression : At line:1 char:23
+ Write-Host asdasdasd a&&&&&asdASsdad asd a ada &7
The token '&&' is not a valid statement separator in this version.