PowerShell remoting allows you to run PowerShell commands on a Windows machine from another computer. I recently tried to do this from my local machine to a new Azure (resource managed) VM but struggled. I eventually figured it out and thought I’d share how to do it. A few points worth mentioning before we get into it:
- PowerShell remoting is enabled by default since Windows Server 2012
- By default, you can only remote into machines on the same subnet
- For this post I’m using the Windows Server 2012 R2 Datacenter image
Step 1: create a new RM VM
First I create a new VM, using the standard Windows Server 2012 R2 Datacenter image provided by Azure. This is in New > Compute > Windows Server 2012 R2 Datacenter. I choose to create a new resource group during this step.
Step 2: configure the new NSG
Creating that virtual machine will have also created a few other resources, including a Network Security Group. We need to add an **inbound rule **at this point:
Priority: 1100
Source: Any (or your IP address)
Protocol: TCP
Source port range: *
Destination: Any
Destination port range: 5985
Action: Allow
NSG configuration
Step 3: set network profile on the VM
To be able to remote in from outside the subnet, you need to set the network profile:
PS C:\> Set-NetConnectionProfile -NetworkCategory Private
The same thing is achieved by enabling network discovery in Network and Sharing Center > Advanced Sharing Settings > Network Discovery (although this will open a lot of file sharing/printing rules on the firewall, too).
Step 4: set trusted hosts on your local machine and connect
Before connecting, you must update the hosts your local machine trusts. This line of PowerShell will add a wildcard to the TrustedHosts so you can connect to anything:
set-item wsman:\localhost\Client\TrustedHosts -value *
You should now be able to start a remote PowerShell session with your VM using the following:
Enter-PSSession -computerName 13.69.194.136 -Credential robertselway
Conclusion
Remoting in from a machine outside the subnet perhaps isn’t strictly necessary or desirable from a devops point of view (it’s likely if you’re looking to automatically run PowerShell commands, you’ll have your controller node on the local network). However, it can be really handy from a dev/learning point of view. If anyone thinks I’ve missed something or knows a better way, please let me know!