12 August 2015

Allow a specific port through Windows Firewall using PowerShell

By default Windows Firewall is turned on Windows Servers. Instead of turning off whole firewall you should allow only some ports go through. To do this using PowerShell you need only one simple line of code:

New-NetFirewallRule -DisplayName mssql -LocalPort 1433 -Protocol tcp

This example opens Microsoft SQL Server TCP port 1433 for incoming connections. Nice and easy line. Especially handy, when you need to do this using script on multiple servers.

To remove this rule, you should use the following command (mssql being the displayname of the rule):

Remove-NetFirewallRule -DisplayName mssql

11 August 2015

How to get your public IP in PowerShell

Ever wanted to know your public IP address programmatically in PowerShell? Here’s a good oneliner for you:

(Invoke-WebRequest http://myip.eu ).ParsedHtml.body.innerText.Split()[15]

It will get a sample page from myip.eu page, parse this html page body and find in text only version a space splitted part with serial number 15. No warranty though that this page work forever and the page result is formatted the same in future. Still worth a try.

02 February 2015

How to add domain user to local administrator group using PowerShell

All you need is following one-liner:

([ADSI]"WinNT://localhost/administrators,group").psbase.Invoke("Add",([ADSI]"WinNT://domain/user").path)

You need to change the domain/user to your actual domain name and user name (contoso/john for example).

05 January 2015

Get all sites and subnets in AD using PowerShell

I wondered if there is a command like Get-ADSite or Get-ADSubnet in PowerShell but it turns out there isn’t.

After surfing around the net I ended up writing this oneliner:

Get-ADObject -SearchB (Get-ADRootDSE).ConfigurationNamingContext -f {objectClass -eq "site"} -Pr siteObjectBL | %{'';$_.Name;foreach($s in $_.siteObjectBL){$s}}

The output lists all sites separated by empty line. For each sites all subnets are listed.