Home > Blockchain >  I had PowerShell Hash table with multiple values in it. every 3 keys have common prefix, Which i nee
I had PowerShell Hash table with multiple values in it. every 3 keys have common prefix, Which i nee

Time:12-13

$keyvaultName = 'KeyVaultName'
$secrets = Get-AzKeyVaultSecret -VaultName $keyvaultName

$keys = @{}

foreach ($secret in $secrets) {
    $secretName = $secret.name

    $key = (Get-AzKeyVaultSecret -VaultName $keyvaultName -name $secretName).SecretValueText
    $keys.Add("$secretName", "$key")
}

Getting the output and stored in $keys. $keys output had multiple attributes and forms a set of 3 with common prefix as given below.

$keys.example-APPid 
$keys.example-id 
$keys.example-secret 

$keys.example1-appid
$keys.example1-id 
$keys.example1-secret

so on.

Need to corelate and reference these 3 values in foreach loop. Please suggest an Work around for this.

How to reference and corelate these output values with common prefixes in foreach loop

CodePudding user response:

You can use the Group-Object cmdlet with a calculated property:

# Sample input hashtable
$keys = @{}
$keys.'example-APPid' = 'a1'; $keys.'example-id' = 'a2'; $keys.'example-secret' = 'a3' 
$keys.'example1-appid' = 'b1'; $keys.'example1-id' = 'b2'; $keys.'example1-secret' = 'b3'

$keys.GetEnumerator() | # enumerate the hashtable's entries
   Group-Object -Property { $_.Key -replace '-. $' } | # group by key prefix (before "-")
   ForEach-Object { # process each resulting group
      [pscustomobject] @{
         Prefix = $_.Name
         Keys = $_.Group.Key
         Values = $_.Group.Value
      }
   }

Output:

Prefix   Keys                                           Values
------   ----                                           ------
example  {example-id, example-secret, example-APPid}    {a2, a3, a1}
example1 {example1-appid, example1-id, example1-secret} {b1, b2, b3}
  • Related