PowerShell/Scripts/add-firewall-rules.ps1

55 lines
1.6 KiB
PowerShell
Raw Normal View History

2021-09-27 10:38:12 +02:00
<#
2021-07-13 19:03:30 +02:00
.SYNOPSIS
Adds firewall rules for executables (needs admin rights).
2021-10-04 21:29:23 +02:00
.DESCRIPTION
2022-01-29 12:47:46 +01:00
This PowerShell script adds firewall rules for the given executable. Administrator rights are required.
2021-10-12 21:51:51 +02:00
.PARAMETER PathToExecutables
Specifies the path to the executables.
.PARAMETER Direction
Specifies the direction for the firewall rule. Can be 'Inbound' or 'Outbound'. Default is 'Inbound'.
.PARAMETER Profile
Specifies the firewall profile. Can be 'Domain', 'Private', or 'Public'. Multiple values can be specified as an array.
2021-07-13 19:03:30 +02:00
.EXAMPLE
PS> ./add-firewall-rules.ps1 -PathToExecutables C:\MyApp\bin -Direction Outbound -Profile Private
2021-07-13 19:03:30 +02:00
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
2022-09-06 21:42:04 +02:00
Author: Markus Fleschutz | License: CC0
2021-01-28 15:02:16 +01:00
#>
#Requires -RunAsAdministrator
param(
[string]$PathToExecutables = "",
[string]$Direction = "Inbound",
[array]$FirewallProfile = @("Domain", "Private")
)
2021-02-01 08:25:03 +01:00
try {
if (-not $PathToExecutables) {
$PathToExecutables = Read-Host "Enter path to executables"
2021-01-28 15:02:16 +01:00
}
2021-02-01 08:25:03 +01:00
$AbsPath = Convert-Path -Path $PathToExecutables
$Executables = Get-ChildItem -Path $AbsPath -Filter "*.exe"
2021-02-01 08:25:03 +01:00
if (-not $Executables) {
Write-Warning "No executables found. No Firewall rules have been created."
Read-Host "Press Enter to continue..."
return
}
foreach ($exe in $Executables) {
$exeName = $exe.Name
$exeFullPath = $exe.FullName
2021-01-28 15:02:16 +01:00
Write-Output "Adding firewall rule for $exeName"
New-NetFirewallRule -DisplayName $exeName -Direction $Direction -Program $exeFullPath -Profile $FirewallProfile -Action Allow
2021-01-28 15:02:16 +01:00
}
2021-02-01 08:25:03 +01:00
Write-Host -ForegroundColor Green "Done"
2021-02-01 08:25:03 +01:00
} catch {
Write-Error "Error in line $($_.InvocationInfo.ScriptLineNumber): $($_.Exception.Message)"
2021-01-28 15:02:16 +01:00
}