Create a Network Security Group Rule using PowerShell

My last post, https://www.techdiction.com/2016/02/11/configuring-winrm-over-https-to-enable-powershell-remoting/, covered enabling WinRM over HTTPS on an Azure VM. After forwarding the steps to colleagues it was pointed out that some of the steps could be simplified with some PowerShell. My next couple of posts will cover how different parts of my initial process could be automated, starting with creation of the network security group rule.

I want to say thanks to Andy Slowey, Technology Specialist at Microsoft Research who suggested some improvements, carried out some testing and ironed out some of the bugs in my PowerShell.

The PowerShell below creates the network security group rule for WinRM over HTTPS, the rule can easily be modified for other purposes. It is created on the network security group applied to the first NIC attached to the VM. As always I am sure my PowerShell can be optimised in places, feel free to suggest improvements in the comments section.

 $subscriptionname = "<your_subscription_name>"
$rgname = "<resource_group_vm_is_in>"
$vmname = "<vm_name>"


# Authenticate to Azure 
Login-AzureRmAccount
Select-AzureRmSubscription -SubscriptionName $subscriptionname

# Get the VM we need to congigure
$vm = Get-AzureRmVM -ResourceGroupName $rgname -Name $vmname

# Get the name of the first NIC in the VM
$nic = Get-AzureRmNetworkInterface -ResourceGroupName $rgname -Name (Get-AzureRmResource -ResourceId $vm.NetworkInterfaceIDs[0]).ResourceName

# Get the network security group attached to the NIC
$nsg = Get-AzureRmNetworkSecurityGroup  -ResourceGroupName $rgname  -Name (Get-AzureRmResource -ResourceId $nic.NetworkSecurityGroup.Id).Name 

# Add the new NSG rule, and update the NSG
$nsg | Add-AzureRmNetworkSecurityRuleConfig -Name "WinRM_HTTPS" -Priority 1100 -Protocol TCP -Access Allow -SourceAddressPrefix * -SourcePortRange * -DestinationAddressPrefix * -DestinationPortRange 5986 -Direction Inbound   | Set-AzureRmNetworkSecurityGroup 

My next post will cover automating the server side configuration for WinRM over HTTPS without needing to log onto the Azure virtual machine.