Firewall – How to add a firewall rule with PowerShell

firewallpowershellremote desktop

I made a very simple script to enable Remote Desktop connections on a computer:

# Allow Remote Desktop connections
(Get-WmiObject -Class "Win32_TerminalServiceSetting" -Namespace root\cimv2\terminalservices).SetAllowTsConnections(1)

# Allow low-secutiry connections
(Get-WmiObject -class "Win32_TSGeneralSetting" -Namespace root\cimv2\terminalservices -Filter "TerminalName='RDP-tcp'").SetUserAuthenticationRequired(0)

Now, I wish to finish it, adding a rule for Remote Desktop into Windows Firewall. How I can accomplish this?

BTW: Using Windows 7

Clarification:

Today I enable Remote Desktop manually via "Remote Settings" on "Control Panel\System and Security\System". Doing this way, Windows automatically adds a Firewall Rule to allow incoming remote desktop connections. Fine.

However, using my script above, this last step is not done. On this very configuration screen Windows shows me a reminder message "You must enable the Windows Firewall exception for Remote Desktop"

The question is exactly that: How I can automate this step? Today I do this manually on every computer I install.

Best Answer

You can use NETSH in PowerShell. To enable the Remote Desktop rule, you can use this command

netsh advfirewall Firewall set rule group="Remote Desktop" new enable=yes