Trying to update the KeyVault Secrets Tag from CSV

Trying to update the KeyVault Secrets Tag. All is good except for the tag. The tag is not getting updated.

I tried with the below code & CSV.

$keyVaultName = "test-kv01"
$data = Import-Csv "C:\temp\kv.csv"

# Iterate over each row in the CSV and create/update the secrets in the Key Vault
foreach ($row in $data) {
    $secretName = $row.Name
    $secretValue = $row.Secret
    $secretTags = ConvertFrom-Json -InputObject $row.Tags

    # Create or update the secret
    Set-AzKeyVaultSecret -VaultName $keyVaultName -Name $secretName -SecretValue $secretValue -Tag $secretTags
}

<# Sample CSV
Name,Secret,Tags
secret1,secret01,@{ 'Severity' = 'medium'; 'IT' = 'true'}
secert2,secret02,@{ 'Severity' = 'medium'; 'IT' = 'true'}

#>

Hi, welcome back :wave:

The -Tag parameter expects a hashtable, but by default ConvertFrom-Json outputs a PSCustomObject.

If you’re using PowerShell 7.x then ConvertFrom-Json has an -AsHashTable parameter, otherwise you’ll have to build it yourself:

$json = @"
{
    "Name": "Bob",
    "Country": "United Kingdom"
}
"@

$obj = $json | ConvertFrom-Json

$hashtable = @{}

foreach ($key in $obj.PSObject.Properties) {
    $hashtable.Add($key.Name,$key.Value)
}
1 Like

Thank you :slight_smile: . I also fixed that in another way.

$keyVaultName = "KeyVault01"
$data = Import-Csv "C:\temp\test.csv"
# Iterate over each row in the CSV and create/update the secrets in the Key Vault
foreach ($row in $data) {
    Try {
    $secretName = $row.Name
    $secretValue = convertto-securestring -string $row.Secret -asplaintext -force
    $TagName =$row.TagName
    $TagValue = $row.TagValue
    # Create or update the secret
    Set-AzKeyVaultSecret -VaultName $keyVaultName -Name $secretName -SecretValue $secretValue -Tag @{"$TagName"="$TagValue"}
}
catch
{
Write-Output "Error: $($_.Exception.Message)"
}

}
<#
Name,Secret,TagName,TagValue
secret1,secret01,Biswajit,IT
secert2,secret02,Siva,IT
#>