Skip to content

Instantly share code, notes, and snippets.

@pcgeek86
Last active August 29, 2015 14:17
Show Gist options
  • Save pcgeek86/0b9019f3b2b26e96fdbf to your computer and use it in GitHub Desktop.
Save pcgeek86/0b9019f3b2b26e96fdbf to your computer and use it in GitHub Desktop.
A simple PowerShell function to simplify the process of establishing a RDP connection to a Microsoft Azure Virtual Machine.
function azrdp {
<#
.Author
Trevor Sullivan <pcgeek86@gmail.com>
.Description
Invoke a RDP session to an Azure Virtual Machine, without having to type the
Cloud Service name or Virtual Machine name.
.Outputs
None
.Links
http://trevorsullivan.net
http://twitter.com/pcgeek86
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[switch] $PromptSubscription
)
$AzureReauthenticate = {
$AuthResult = Add-AzureAccount 3>&1;
if ($AuthResult -match 'User canceled authentication') {
Write-Error -Message 'User canceled authentication, exiting function.';
return;
}
# Re-invoke the azrdp function using the same arguments that the user passed in originally
$Parameters = (Get-PSCallStack)[1].InvocationInfo.BoundParameters;
& $PSCmdlet.MyInvocation.MyCommand.Name @Parameters;
}
try {
if ($PromptSubscription) {
Write-Verbose -Message 'Prompting for Azure subscription.';
$SubscriptionList = Get-AzureSubscription;
if (!$SubscriptionList) {
& $AzureReauthenticate;
}
$Subscription = $SubscriptionList | Select-Object -Property SubscriptionName,SubscriptionId | Out-GridView -PassThru -Title 'Select your Azure Subscription';
if (!$Subscription) {
Write-Warning -Message 'No Azure subscription was selected.';
return;
}
Select-AzureSubscription -SubscriptionName $Subscription.SubscriptionName;
}
$VM = Get-AzureVM -ErrorAction Stop | Out-GridView -PassThru -Title 'Select your Azure Virtual Machine';
if (!$VM) {
Write-Warning -Message 'No virtual machine was selected.';
return;
}
Write-Verbose -Message ('Invoking Remote Desktop session to {0}\{1}' -f $VM.ServiceName, $VM.Name);
Get-AzureRemoteDesktopFile -ServiceName $VM.ServiceName -Name $VM.Name -Launch;
}
catch [System.ArgumentException] {
if ($PSItem.Exception.Message -match 'Add-AzureAccount') {
& $AzureReauthenticate -;
}
}
catch [System.ApplicationException] {
if ($PSItem.Exception.Message -match 'No default subscription') {
& $AzureReauthenticate;
}
}
}
@pcgeek86
Copy link
Author

@Stefan: You're welcome! Thanks for commenting.

Cheers,
Trevor Sullivan
Microsoft MVP: PowerShell
http://trevorsullivan.net
http://twitter.com/pcgeek86

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment