Home > database >  I want to create a function that will get a list of Key Vaults that don't have any virtual netw
I want to create a function that will get a list of Key Vaults that don't have any virtual netw

Time:01-18

The script parts work solo, but when run together generate the wrong output (i.e. shows KeyVaults that do have virtual networks. How do I fix this?

 function Get-KeyVault {

 [CmdletBinding()]

param (

    #Enter the path you would like to save the excel output  
    [Parameter(Mandatory)]
    [string]
    $Path         
    )

 $KeyVaults= Get-AzKeyVault
 $result=@()  

  foreach($keyvault in $KeyVaults)
 {
     $NetworkAcls=(Get-AzKeyVault -VaultName $keyvault).NetworkAcls
     $VirtualNetworkResourceIds= $NetworkAcls.VirtualNetworkResourceIds
     if ($VirtualNetworkResourceIds -eq $null)
         {
          $obj = [PSCustomObject]@{
         Name= $keyvault.VaultName
         ResourceGroup= $keyvault.ResourceGroupName
         Location= $keyvault.Location
         }
   $result  = $obj
        }
     }
    $result | Export-Csv -Path $Path -NoTypeInformation
 }

CodePudding user response:

Your code seems to be fine except for the below part :

$NetworkAcls=(Get-AzKeyVault -VaultName $keyvault).NetworkAcls

Here in the -VaultName you are declaring $keyvault which is a object from the list of keyvaults not the keyvault name , for which the $NetworkACLs and $VirtualNetworkResourceIds doesn't provide any output and the if statement gets nullified resulting in storing all the keyvault names , their resourcegroup names and locations in the custom object.

To Fix that you will have to use the below so that the correct output is stored in the NetworkAcls variable and the next steps :

$NetworkAcls=(Get-AzKeyVault -VaultName $keyvault.VaultName).NetworkAcls

Complete code :

function Get-KeyVault {

 [CmdletBinding()]

param (

    #Enter the path you would like to save the excel output  
    [Parameter(Mandatory)]
    [string] $Path         
    )

 $KeyVaults= Get-AzKeyVault
 $result=@()  

  foreach($keyvault in $KeyVaults)
 {
     $NetworkAcls=(Get-AzKeyVault -VaultName $keyvault.VaultName).NetworkAcls
     $VirtualNetworkResourceIds= $NetworkAcls.VirtualNetworkResourceIds
     if ($VirtualNetworkResourceIds -eq $Null)
         {
          $obj = [PSCustomObject]@{
         Name= $keyvault.VaultName
         ResourceGroup= $keyvault.ResourceGroupName
         Location= $keyvault.Location
         }
   $result  = $obj

        }
     }
    $result | Export-Csv -Path $Path -NoTypeInformation
 }

I tested the same in my environment as well as below :

KV with Network Policy:

enter image description here

Issue output :

enter image description here

After applying fix :

enter image description here

  •  Tags:  
  • Related