Powershell script to detect the Windows Azure SDK in Azure Cloud Service VM and fix the Powershell execution issue


When you try to run Powershell commands on Windows Azure Cloud Service (PaaS) VM you may have seen exception as below:

PS D:\Users\avkash> Add-PSSnapin Microsoft.WindowsAzure.ServiceRuntime

Add-PSSnapin : Cannot add Windows PowerShell snap-in Microsoft.WindowsAzure.ServiceRuntime because it is already added.
Verify the name of the snap-in and try again.
At line:1 char:13
+ Add-PSSnapin <<<< Microsoft.WindowsAzure.ServiceRuntime
+ CategoryInfo : InvalidArgument: (Microsoft.WindowsAzure.ServiceRuntime:String) [Add-PSSnapin], PSArgume ntException
+ FullyQualifiedErrorId : AddPSSnapInRead,Microsoft.PowerShell.Commands.AddPSSnapinCommand

I have create a Powershell script which auto detect the Windows Azure SDK version runtime in the Azure VM and then  fix this problem in registry and set the Role Busy as below:

[xml] $RoleModelXml = Get-Content "E:\RoleModel.xml"
$sdkVersion = $RoleModelXml.RoleModel.Version
Write-Output ("---------------------------------------")
Write-Output("Your SDK Version is: " + $sdkVersion)
Write-Output("---------------------------------------")

Write-Output("")
Write-Output("Now Setting SDK Version in Registry: " + $sdkVersion.substring(0,3))
Write-Output("---------------------------------------")

$finalSDKVersion = $sdkVersion.substring(0,3)
$fixedAssemblyName = "Microsoft.WindowsAzure.ServiceRuntime.Commands, Version=" + $finalSDKVersion + ".0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

$Registry_Key = “HKLM:\Software\Microsoft\PowerShell\1\PowerShellSnapIns\Microsoft.WindowsAzure.ServiceRuntime\"
Set-ItemProperty -path $Registry_Key -name Version -value $finalSDKVersion
Set-ItemProperty -path $Registry_Key -name PowerShellVersion -value 2.0
Set-ItemProperty -path $Registry_Key -name AssemblyName -value $fixedAssemblyName


#Validate the registry
Write-Output("*** --- Validating the registry change *** ----")
Get-ItemProperty -path $Registry_Key -name Version
Get-ItemProperty -path $Registry_Key -name PowerShellVersion
Get-ItemProperty -path $Registry_Key -name AssemblyName


$AzureSnapIn = "Microsoft.WindowsAzure.ServiceRuntime"

if ( (Get-PSSnapin -Name $AzureSnapIn -ErrorAction SilentlyContinue) -eq $null )
{

Add-PsSnapin $AzureSnapIn
}
else
{
$message = "PsSnapin " + $AzureSnapIn + " already loaded!!"
Write-Output($message);
}


#Settings the Role busy
Write-Output("*** --- Setting Role Busy *** ----")
Set-RoleInstanceStatus -busy
Comments (0)