<# .SYNOPSIS NAME Create-WindowsFirewallRule.ps1 This script creates a new Windows Firewall rule on the local computer. .DESCRIPTION This script creates a new Windows Firewall rule on the local computer. .PARAMETER NewPortName Set the Name of the new port. This name shows up as the name of the associated rule with this port. PARAMETER ALIAS: PortName or Name EXAMPLE: Create-WindowsFirewallRule.ps1 -NewPortName "SCOM Management Port TCP 5723" .PARAMETER NewPortType Set the New Port Type. PARAMETER ALIAS: PortType or Type OPTIONS: TCP or UDP DEFAULT: TCP EXAMPLE: Create-WindowsFirewallRule.ps1 -NewPortType TCP .PARAMETER NewPortNumber Set the New Port Number. PARAMETER ALIAS: PortNumber or Number EXAMPLE: Create-WindowsFirewallRule.ps1 -NewPortNumber 5723 .PARAMETER NewPortScope Define the scope of the new firewall rule. PARAMETER ALIAS: PortScope or Scope OPTIONS: "*" or "LocalSubnet" or "Subnet/SubnetMask" or a combination (* overrides any other items) DEFAULT: "*" (All) EXAMPLE: Create-WindowsFirewallRule.ps1 -NewPortScope "LocalSubnet,10.10.10.0/255.255.255.0" .PARAMETER NewPortStatus This controls whether the rule is enabled ($True) or disabled ($False) PARAMETER ALIAS: PortStatus or Status OPTIONS: $True or $False DEFAULT: $True EXAMPLE: Create-WindowsFirewallRule.ps1 -NewPortStatus $False .PARAMETER Verbose The logging mode the script runs in. EXAMPLE: Create-WindowsFirewallRule.ps1 -Verbose .PARAMETER Debug Enables debug logging. EXAMPLE: Create-WindowsFirewallRule.ps1 -Debug .EXAMPLE Create-WindowsFirewallRule.ps1 -Name "SCOM TCP 5723" -Number 5723 -Type TCP .EXAMPLE Create-WindowsFirewallRule.ps1 -Name "SCOM UDP 5723" -Number 5723 -Type UDP .EXAMPLE Create-WindowsFirewallRule.ps1 -verbose -Name "HTTPS TCP 443" -Number 443 -Type TCP -Status $False .EXAMPLE Create-WindowsFirewallRule.ps1 -Name "HTTP TCP 80" -Number 80 -Type TCP -Scope LocalSubnet .EXAMPLE Create-WindowsFirewallRule.ps1 -Name "HTTP TCP 80" -Number 80 -Type TCP -Scope "LocalSubnet,10.10.10.0/255.255.255.0" .NOTES NAME: Create-WindowsFirewallRule.ps1 AUTHOR: Sean Metcalf AUTHOR EMAIL: Sean Metcalf AT MetcorpConsulting [dot com CREATION DATE: 10/28/2011 LAST MODIFIED DATE: 11/01/2011 LAST MODIFIED BY: Sean Metcalf INTERNAL VERSION: 01.11.11.01.20 RELEASE VERSION: 0.1.0 VERSION LOG * 10/27/2011: Initial Script Creation * 11/01/2011: Add parameter control and Get-Help extended information. #### ## Based on code from http://pshscripts.blogspot.com/2010/03/enable-firewallport2ps1.html #### #> # This Powershell script leverages some features only available with Powershell version 2.0. # As such, there is no guarantee it will work with earlier versions of Powershell. # Requires -Version 2.0 ##################### # Script Parameters # ##################### Param ( [parameter(Mandatory=$True)] [alias("PortName","Name")] [string]$NewPortName, [parameter(Mandatory=$True)] [alias("PortType","Type")] [ValidateSet("TCP", "UDP")] [string]$NewPortType, [parameter(Mandatory=$True)] [alias("PortNumber","Number")] [ValidateRange(1,65535)] [string]$NewPortNumber, [alias("PortScope","Scope")] [string] $NewPortScope = "*", [alias("PortStatus","Status")] [switch] $NewPortStatus = $TRUE ) ############################ # Configure Script Options # ############################ Write-Output "Reading configured script options... `r " Write-Verbose "Setting default options for script parameters... `r " Switch ($Verbose) { ## OPEN Switch Verbose $True { $VerbosePreference = "Continue" ; Write-Output "Script logging is set to verbose. `r " } $False { $VerbosePreference = "SilentlyContinue" ; Write-Output "Script logging is set to normal logging. `r " } } ## OPEN Switch Verbose Switch ($Debug) { ## OPEN Switch Debug $True { $DebugPreference = "Continue" ; Write-Output "Script Debug logging is enabled. `r " } $False { $DebugPreference = "SilentlyContinue" ; } } ## OPEN Switch Debug Write-Verbose "Check script parameters and based on setting configure proper script options & inform user... `r " ############################### # Set Environmental Variables # ############################### write-output "Setting environmental variables... `r " $CurrentComputerName = $env:ComputerName Write-Debug "Variable CurrentComputerName is set to $CurrentComputerName `r " $CurrentUserName = $env:UserName Write-Debug "Variable CurrentUserName is set to $CurrentUserName `r " $DomainDNS = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Name #Get AD Domain (lightweight & fast method) $TimeVal = get-date -uformat "%Y-%m-%d-%H-%M" Write-Debug "Variable TimeVal is set to $TimeVal `r " $LogDir = "C:\temp\Logs\" #Standard location for script logs Write-Debug "Variable LogDir is set to $LogDir `r " $DateTime = Get-Date #Get date/time Write-Debug "Variable DateTime is set to $DateTime `r " IF (!(Test-Path $LogDir)) {new-item -type Directory -path $LogDir} # Script Specific $NET_FW_IP_PROTOCOL_UDP = 17 $NET_FW_IP_PROTOCOL_TCP = 6 # Script Logging $ScriptName = $MyInvocation.mycommand.name $ScriptLogName = $ScriptName.replace(".ps1", ".log") $LogFileName = "$ScriptLogName-$DomainDNS-$TimeVal.log" $LogFile = $LogDir + $LogFileName Write-Debug "Variable LogFile is set to $LogFile `r " ################## # Start Logging # ################## # Log all configuration changes shown on the screen during run-time in a transcript file. This # inforamtion can be used for troubleshooting if necessary Write-Verbose "Start Logging to $LogFile `r " Start-Transcript $LogFile -force ## Process Start Time $ProcessStartTime = Get-Date Write-Verbose " `r " write-Verbose "Script initialized by $CurrentUserName and started processing at $ProcessStartTime `r " Write-Verbose " `r " ######################## # Create Firewall Rule # ######################## Write-Output "Creating new firewall rule for $NewPortName ($NewPortType $NewPortNumber) `r " Write-Verbose "Create the firewall manager object. `r " $fwMgr = New-Object -COM HNetCfg.FwMgr Write-Verbose "Get the current profile for the local firewall policy. `r " $profile = $fwMgr.LocalPolicy.CurrentProfile IF ($profile.FirewallEnabled -eq $True) { Write-Output "Windows Firewall is Enabled `r " } ELSE { Write-Output "Windows Firewall is Enabled `r " } Write-Verbose "Display Windows Firewall Rules `r " Write-Output "Current Globally Open Firewall Rules: `r " Write-Output "-------------------------------------" $profile.GloballyOpenPorts | ft name, ipversion, protocol, port, scope, remoteaddresses, enabled -auto Write-Verbose "Set the options for the new Firewall Rule `r " $FirewallPort = New-Object -COM HNetCfg.FWOpenPort $FirewallPort.Name = $NewPortName Switch ($NewPortType) { ## OPEN Switch NewPortType "TCP" { $FirewallPort.Protocol = $NET_FW_IP_PROTOCOL_TCP } "UDP" { $FirewallPort.Protocol = $NET_FW_IP_PROTOCOL_UDP } } ## CLOSE Switch NewPortType $FirewallPort.Port = $NewPortNumber $FirewallPort.RemoteAddresses = "*" $FirewallPort.Enabled = $NewPortStatus Write-Verbose "Create the new Firewall Rule `r " $profile.GloballyOpenPorts.Add($FirewallPort) Write-Verbose "Display all Globally Open Firewall Rules `r " $profile = $fwMgr.LocalPolicy.CurrentProfile Write-Output "Globally Open Firewall Rules: `r " Write-Output "-----------------------------" $profile.GloballyOpenPorts | ft name, ipversion, protocol, port, scope, remoteaddresses, enabled -auto Write-Output "Active Service Firewall Rules: `r " Write-Output "------------------------------" $profile.Services | ft name, ipversion, scope, remoteaddresses, enabled -auto Write-Output "Active Authorized Applications Firewall Rules: `r " Write-Output "----------------------------------------------" $profile.AuthorizedApplications | ft name, ipversion, scope, enabled -auto $NewProfile = $profile.GloballyOpenPorts | where { $_.Name -like "*$NewPortName*" } IF ($NewProfile) { Write-Output "New firewall rule $NewPortName for $NewPortType $NewPortNumber created successfully `r" } ELSE { Write-Warning "New firewall rule $NewPortName for $NewPortType $NewPortNumber was not created. `r" } ######################################## # Provide Script Processing Statistics # ######################################## $ProcessEndTime = Get-Date Write-output "Script started processing at $ProcessStartTime and completed at $ProcessEndTime." `r $TotalProcessTimeCalc = $ProcessEndTime - $ProcessStartTime $TotalProcessTime = "{0:HH:mm}" -f $TotalProcessTimeCalc Write-output "" `r Write-output "The script completed in $TotalProcessTime." `r Write-Output " `r " ################# # Stop Logging # ################# #Stop logging the configuration changes in a transript file Stop-Transcript Write-output "Review the logfile $LogFile for script operation information." `r