Automating Remote Desktop Connection to Azure Lab VMs using PowerShell

Last few posts have been rather lengthy so here’s a quick one.

Recently I’ve been doing a lot of lab work in Azure and found myself often creating numerous Windows VMs and needing to RDP into them once the provisioning process was done.

There are of course numerous ways to achieve this, from manually running mstsc to using an Azure Bastion Host but for these lab environments I wanted utter simplicity - one command and no entering credentials.

Getting the VM IPs is easy enough with the Azure CLI (which I also use to to build the labs), but the trickier part is injecting the credentials as mstsc doesn’t have a parameter for that. The best method I found was to use cmdkey to save the credentials into Credential Manager, run the mstsc client which will automatically use them, and then delete immediately them.

Here’s the PowerShell function I’ve been using for this, I added it to my PowerShell profile so it’s always available.

function RDPToAzureVMs ([string]$ResouceGroup="lab"){
    $VMIPs = az vm list -g $ResouceGroup -d --query "[].publicIps" -o tsv
    $RDPCreds = Import-CliXml "$env:USERPROFILE\labs\windowscreds.xml"
    $Username = $RDPCreds.UserName
    $VMIPs | % {
        cmdkey /generic:$_ /user:$Username /pass:$($RDPCreds.GetNetworkCredential().Password) | Out-Null
        mstsc /v $_
    Start-Sleep -Seconds 1
    $VMIPs | % {
        cmdkey /delete:$_ | Out-Null

A few things to note:

  • The Azure CLI needs to be installed. This is only used to obtain the VM public IPs, so you can easily substitute for PowerShell if that is your preference.
  • I keep the credentials in an encrypted XML file, you can generate this with a PSCredential object and Export-Clixml
    • Get-Credential | Export-Clixml <Path>

By default this will attempt to RDP to all VMs inside the Azure Resource group named lab, there is a -ResourceGroup parameter which can be passed to change that.

This function can of course be adapted to work with other non-Azure environments, the only part that needs to change is the command to obtain VM IPs.

That’s all, thanks for reading.

If you enjoyed this post consider sharing it on , , , or , and .