Script Sample - VM Operations - Export VM Configurations

@20aman    Dec 11, 2018

Exporting a VM configuration is a best practice that you should be doing before altering any configurations on the Virtual Machine. Any action that can corrupt the VM or its configurations should be preceded by exporting of VM's configurations. This allows you to be able to refer back to these configurations and recreate the VM in case of any unexpected scenario.

With the Script sample in this post, you can take the export of multiple VMs by providing the same in a csv configuration file. This file is very simple and the creation of this file itself can also be automated.

The script can also be altered to take an export of all the VMs in the environment.

Script Requirements

The script requires you to populate the configurations CSV file. The sample CSV file is also provided along with the script. This configurations file should have the following columns:

  1. Computer - Name of the VM in Azure
  2. ResourceGroupName - Resource Group of the VM

Script Working

This is a very simple but one of the most reusable script. It simply takes the export in two steps.

First it fetches the VM as shown below:

$currentVm = Get-AzureRmVM -ResourceGroupName $ResourceGroupName -Name $virtualMachineName -ErrorAction Stop

Then, it takes the export by using the below command.

$currentVm | ConvertTo-Json -Depth 100 | Out-File -FilePath $fileName

The Trick: The most important thing is the Depth parameter when using ConvertTo-Json cmdlet. If you do not specify this then nested properties may not export properly. Specifying a large enough depth ensures that all nested properties are also exported.

The script encapsulates all this logic into a reusable function. It also provides the best practices template to invoke this function. Note: Check the comments marked with "ToDo" where you should be making the changes.

Location of the Script

You can find this script in GitHub at this location: Export-VMConfig.ps1





Comments powered by Disqus