# Script Version 1.3
<#
===========================================================================================
| |
| User Settings |
| |
===========================================================================================
#>
# Path to a plain text file containing IP addresses.
# Note: The file must contain a single IP address per line.
[string] `
$ipListFile = "$PSScriptRoot\Ipv4.txt"
# An Array with additional IP addresses to block.
[string[]] `
$ipArray = @()
<#
===========================================================================================
| |
| Functions |
| |
===========================================================================================
#>
function Show-WelcomeScreen {
Clear-Host
Write-Host ""
Write-Host " $($host.ui.RawUI.WindowTitle)"
Write-Host " +=======================================+"
Write-Host " | |"
Write-Host " | This script will add firewall rules |"
Write-Host " | to block network traffic for the IP |"
Write-Host " | addresses specified in the input file |"
Write-Host " | and/or defined in this script file. |"
Write-Host " | |"
Write-Host " +=======================================+"
Write-Host ""
Write-Host " Input File Path: $ipListFile" -ForegroundColor DarkGray
Write-Host ""
Write-Host " IP addresses hardcoded in this script: $($ipArray.Count)" -ForegroundColor DarkGray
Write-Host ""
}
function Confirm-Continue {
Write-Host " Press 'Y' key to continue or 'N' key to exit."
Write-Host ""
Write-Host " -Continue? (Y/N)"
do {
$key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
$char = $key.Character.ToString().ToUpper()
if ($char -ne "Y" -and $char -ne "N") {
[console]::beep(1500, 500)
}
} while ($char -ne "Y" -and $char -ne "N")
if ($char -eq "N") {Exit(1)} else {Clear-Host}
}
function Show-GoodbyeScreen {
Write-Host "Operation Completed!" -BackgroundColor Black -ForegroundColor Green
Write-Host ""
Write-Host "Press any key to exit..."
$key = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown")
}
function Add-FirewallRules {
param (
[string]$ipListFile,
[string[]]$ipArray
)
Write-Host "Compiling internal C# code..."
# Natural Sorting C# Snippet
Add-Type -TypeDefinition '
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
public static class NativeMethods {
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
public static extern int StrCmpLogicalW(string first, string second);
}
public class NaturalStringComparer : IComparer<string> {
public int Compare(string first, string second) {
return NativeMethods.StrCmpLogicalW(first, second);
}
}
'
Write-Host "Fetching computer's firewall rules..."
$ruleGroupName = "$env:COMPUTERNAME IP Blocks"
[CimInstance[]]$currentRules = Get-NetFirewallRule -Group $ruleGroupName -ErrorAction SilentlyContinue
Write-Host "Building IP address collection..."
$comparer = [NaturalStringComparer]::new()
$sortedSet = [System.Collections.Generic.SortedSet[string]]::new($ipArray, $comparer)
if (Test-Path $ipListFile) {
Write-Host "Fetching IP addresses from input file..."
$ipList = Get-Content -Path $ipListFile | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }
foreach ($ip in $ipList) {
$sortedSet.Add($ip) | Out-Null
}
}
if ($sortedSet.Count -eq 0) {
Write-Warning "There are no IP addresses to process."
return
}
$totalItemCount = $sortedSet.Count
$currentItemIndex = 0
Write-Host "Start processing IP address collection..."
Write-Host ""
foreach ($ip in $sortedSet) {
$currentItemIndex +=1
Write-Host "[$currentItemIndex of $totalItemCount] IP address: $ip"
$ruleNameInbound = "IP Block (Inbound) ($ip)"
$currentRules | Where-Object {
$_.DisplayName -eq $ruleNameInbound
} -ErrorAction SilentlyContinue | Remove-NetFirewallRule
Write-Host "Adding firewall rule to block inbound traffic..." -ForegroundColor DarkGray
[CimInstance]$ruleInbound =
New-NetFirewallRule `
-DisplayName "$ruleNameInbound" `
-Description "This rule disables incoming traffic for address: $ip" `
-Group "$ruleGroupName" `
-Direction "Inbound" `
-Action "Block" `
-RemoteAddress "$ip" `
-Profile "Any" `
-Enabled "True" `
-LocalAddress "Any" `
-InterfaceType "Any"
$ruleNameOutbound = "IP Block (Outbound) ($ip)"
$currentRules | Where-Object {
$_.DisplayName -eq $ruleNameOutbound
} -ErrorAction SilentlyContinue | Remove-NetFirewallRule
Write-Host "Adding firewall rule to block outbound traffic..." -ForegroundColor DarkGray
[CimInstance]$ruleOutbound =
New-NetFirewallRule `
-DisplayName "$ruleNameOutbound" `
-Description "This rule disables outgoing traffic for address: $ip" `
-Group "$ruleGroupName" `
-Direction "Outbound" `
-Action "Block" `
-RemoteAddress "$ip" `
-Profile "Any" `
-Enabled "True" `
-LocalAddress "Any" `
-InterfaceType "Any"
Write-Host ""
}
}
<#
===========================================================================================
| |
| Main |
| |
===========================================================================================
#>
[System.Console]::Title = "Block IP addresses - by Elektro"
[CultureInfo]::CurrentUICulture = "en-US"
try { Set-ExecutionPolicy -ExecutionPolicy "Unrestricted" -Scope "Process" } catch { }
Show-WelcomeScreen
Confirm-Continue
Add-FirewallRules -ipListFile $ipListFile -ipArray $ipArray
Show-GoodbyeScreen
Exit(0)