Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Update an Azure NSG for my current public ip address, start the virtual machine and launch remote desktop to the VM. Associated blogpost
# My RG
$resourceGroup = "MyResourceGroup"
# VM that will be started after updating the NSG
$VMName = "MyVM"
# NSG Name
$NSGName = "MyResourceGroupNSG"
# RDP File
$RDPFile = "C:\Users\Darren\Desktop\MyVM.rdp"
# Get my Public IP
$ip = Invoke-RestMethod | Select -exp ip
# Login to Azure
Import-Module AzureRM
# Get Sub Info and select Subscription
$SubscriptionName = Get-AzureRmSubscription | sort SubscriptionName | Select SubscriptionName, SubscriptionID
$SubscriptionName = $SubscriptionName.SubscriptionName
Select-AzureRmSubscription -SubscriptionName $SubscriptionName
$SubscriptionID = $SubscriptionName.SubscriptionId
# Get NSG
$NSG = Get-AzureRmNetworkSecurityGroup -ResourceGroupName $resourceGroup -Name $NSGName
# Current IP in the RDP Rule
write-host "Current NSG RDP Rule IP is" $NSG.SecurityRules[0].SourceAddressPrefix
write-host "Current External IP is" $IP
# Updating to current external IP if different
if ($NSG.SecurityRules[0].SourceAddressPrefix -ne $ip) {
Set-AzureRmNetworkSecurityRuleConfig -NetworkSecurityGroup $NSG -Name $NSG.SecurityRules[0].Name -SourceAddressPrefix $ip -Protocol * -SourcePortRange * -DestinationPortRange 3389 -Access Allow -DestinationAddressPrefix * -Priority 100 -Direction Inbound
Set-AzureRmNetworkSecurityGroup -NetworkSecurityGroup $NSG
# Start VM
$vm = Get-AzureRmVM -ResourceGroupName $resourceGroup -Name $VMName -Status
$PowerState = (get-culture).TextInfo.ToTitleCase(($vm.statuses)[1].code.split("/")[1])
if ($PowerState -eq "Deallocated"){
$vmstatus = Start-AzureRMVM -ResourceGroupName $resourceGroup -Name $VMName
# Connect to VM using RDP Settings File
Start-Process "$env:windir\system32\mstsc.exe" -ArgumentList $RDPFile
write-host "Something went wrong starting $VMName" -foregroundcolor "magenta" -backgroundcolor "yellow"
# Stop VM
# Stop-AzureRMVM -ResourceGroupName $resourceGroup -Name $VMName -Force
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.