Parse Excel variables into powershell

Solution 1:

If as you have commented, you now have the data stored in a CSV file that might look something like this:

 Name,ResourceGroup,Location
 PRD-ITM001,SJAVIRTUALMACHINES,uksouth
 TST-GRSSQL001,SJAVIRTUALMACHINES,uksouth

it has become very simple to import that data and loop through the records like below:

Import-Csv -Path 'c:\scripts\vmtest.csv' | ForEach-Object {
    # combine the VMName with suffix '-Snapshot'
    $snapshotName    = '{0}-Snapshot' -f $_.Name 
    $SnapshotStorage = "Azure-Snapshots" 

    $vm = Get-AzVM -ResourceGroupName $_.ResourceGroup -Name $_.Name

    # using splatting for better readability
    $configParams = @{
        SourceUri    = $vm.StorageProfile.OsDisk.ManagedDisk.Id
        Location     = $_.Location
        CreateOption = 'copy'
    }
    $snapshot = New-AzSnapshotConfig @configParams

    New-AzSnapshot -Snapshot $snapshot -SnapshotName $snapshotName -ResourceGroupName $_.ResourceGroup
}

Note that the above code assumes your CSV uses the (default) comma as delimiter character. If in your case this is some other character, append parameter -Delimiter followed by the character the csv uses.

  • Inside a ForEach-Object {..} loop, the $_ automatic variable references the current record from the csv
  • I used Splatting for better readability of the code. This helps on cmdlets that take a long list of parameters and eliminates the use of the backtick.