PowerShell script to open RDP session with an Azure VM

My Teammate Jeremy Foster recently shared some azure goodness that he added into his PowerShell Profile.  Then today, I ran across Brian Farnhill’s “Opening RDP session to an Azure VM with PowerShell” blog post and was inspired to add a simple function to my own PowerShell profile to simplify making RDP connections with my Azure VMs.

From a PowerShell command prompt, I opened my profile in notepad (or the text editor of your choice)

notepad $profile

Then, to the bottom of my profile I added the following function

function rdpvm ($ServiceName,$Name) {
  $vm = (Get-AzureVM -ServiceName $ServiceName -Name $Name)
  if($vm -and $vm.InstanceStatus -eq 'ReadyRole') {
    $rdp = (Get-AzureEndpoint -VM $vm | where { $_.LocalPort -eq 3389})
    $fqdn = (New-Object System.URI $vm.DNSName).Authority
    $port = $rdp.Port
    Write-Host "Opening Remote Desktop Session with $($fqdn):$($port)..."
    Start-Process "mstsc" -ArgumentList "/V:$($fqdn):$($port)"
  }
  else {
    Write-Warning "The VM $($vm.Name) is not running ($($vm.InstanceStatus)).  You should start it first"
  }
}

Now, in the future, when I am working with Azure in PowerShell I can simply run the following to open an RDP session with a VM.  Of course, this assumes I’ve already used “Add-AzureAccount” to sign into my azure subscriptions.

rdpvm -ServiceName <MyCloudServiceName> -Name <MyVMName>

Enabling Remote PowerShell Access for Secondary Administrators

If you want to use PowerShell Remoting to run scripts on a remote computer using an account other than the target machine’s built-in administrator account, you will  need to do a couple of things:

  1. On the target machine, create another user account and add it to the built-in “Administrators” group
  2. Set the HKLM/Software/Microsoft/Windows/CurrentVersion/Policies/System/LocalAccountTokenFilterPolicy (DWORD) to a value of 1 (you may need to add the LocalAccountTokeFilterPolicy DWORD value if it doesn’t exist). See http://support.microsoft.com/kb/942817/en-us for more details. 

Once you can do that you can use a Enter-PSSession or Invoke-Command with the credentials you created to remotely run PowerShell scripts against the target machine.

And yes, this applies to remoting into Azure Virtual Machines as well.  Just be aware that for Azure VMs you will need to import the certificate for the remote VM before you can successfully authenticate. 

For more info, check out Michael Washam’s “Introduction to Remote PowerShell with Windows Azure” and Jennelle Crother’s “The Imperfect Lab: Letting Additional Administrators Remotely Connect to Servers” .