Bart Simons

Bart Simons


Thoughts, stories and ideas.

Bart Simons
Author

Share


Tags


Convert AzureRM scripts to Az

Bart SimonsBart Simons

It has been announced by Microsoft that the brand new Azure Az module will represent the de facto standard for connecting to Azure cloud infrastructures. The truth is that all of your already existing scripts will still work due to the fact that aliases can be enabled. From a technical standpoint it is a good short term solution but that doesn't really bring the idea of future-proofing with itself.

You can enable this short term solution by running:

Enable-AzureRmAlias

Please note that you cannot do this if you have code in your script that imports the old AzureRM module. That will obviously conflict with the aliases of the new Az module. In cases where you still need to use the old AzureRM in your environment, please run:

Disable-AzureRmAlias

To disable all the aliases for the cmdlets.

If you take a closer look at the repository which the Az module is based on (Azure/azure-powershell) you'll see that there is a file called Mappings.json inside the folder src/Accounts/Accounts/AzureRMAlias.  

We can directly download this file like this:

$Mappings = ((Invoke-WebRequest https://raw.githubusercontent.com/Azure/azure-powershell/master/src/Accounts/Accounts/AzureRmAlias/Mappings.json -UseBasicParsing).Content | ConvertFrom-Json)

The mappings variable should now contain a list of Azure related objects. We can now iterate over each object in the root to get a list of all mappings like this:

($Mappings | Get-Member -MemberType NoteProperty) | % {
    $Mappings.$($_.Name) | % {
        ForEach ($Mapping in ($_ | Get-Member -MemberType NoteProperty)) {
            Write-Host $_.$($Mapping.Name) "=>" $Mapping.Name
        }
    }
}

This will output a list of mappings in a readable format. We can use this to create a script that replaces the old cmdlets with new ones. The final script looks like this:

$ScriptFile = "C:\Users\Bart\Desktop\script.ps1"
$Script = (Get-Content $ScriptFile -Raw)

($Mappings | Get-Member -MemberType NoteProperty) | % {
    $Mappings.$($_.Name) | % {
        ForEach ($Mapping in ($_ | Get-Member -MemberType NoteProperty)) {
            $Script = $Script -replace $_.$($Mapping.Name),$Mapping.Name
        }
    }
}

$Script | Set-Content $ScriptFile

This should work, but please note that this only replaces the cmdlet names in your script. Just to be sure, run your scripts to make sure that they still work like they used to do. Do you have suggestions for other readers and/or me? Feel free to leave a comment, all knowledge is welcome.

Bart Simons
Author

Bart Simons

View Comments