Skip to content

Commit d153c1c

Browse files
committed
Create Block-OutboundConnectionsForAnApp.ps1
1 parent 184e4f8 commit d153c1c

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# block outbound connections for an .exe path
2+
[CmdletBinding()]
3+
param (
4+
[Parameter(Mandatory = $true, HelpMessage = "The path to the application")]
5+
[String]$ApplicationPath
6+
)
7+
8+
9+
# Test if application exists
10+
if (-not (Test-Path $ApplicationPath)) {
11+
Write-Warning "'$ApplicationPath' does not exist"
12+
return
13+
}
14+
15+
$fileInfo = Get-Item $ApplicationPath
16+
$appName = $fileInfo.Name
17+
$productName = $fileInfo.VersionInfo.ProductName
18+
$string = ""
19+
20+
if (-not [string]::IsNullOrEmpty($productName)) {
21+
$string = $productName.Trim()
22+
}
23+
else {
24+
$string = $fileInfo.BaseName.Trim()
25+
}
26+
27+
if (-not [string]::IsNullOrEmpty($appName)) {
28+
$string = $string + " - " + $appName
29+
}
30+
31+
$ruleName = "[Custom] Block outbound access for $string ($applicationPath)"
32+
33+
# Test if the rule already exists
34+
try {
35+
$ruleExists = [boolean](Get-NetFirewallRule -Direction Outbound | Where-Object { $_.DisplayName -eq "$ruleName" })
36+
}
37+
catch {
38+
Write-Warning "Failed to check if the rule already exists $($_.Exception.Message)."
39+
}
40+
41+
if ($ruleExists) {
42+
Write-Warning "The rule '$ruleName' already exists"
43+
return
44+
}
45+
46+
# create a new rule
47+
try {
48+
Write-Host -ForegroundColor Cyan "Creating a new rule to block outbound connections for the application: $ApplicationPath"
49+
New-NetFirewallRule -DisplayName $ruleName -Direction Outbound -Program $ApplicationPath -Action Block -Enabled True -ErrorAction Stop
50+
Write-Host -ForegroundColor Green "The rule has been created successfully."
51+
}
52+
catch {
53+
Write-Host "Failed to create the rule. The rule may already exist."
54+
}

0 commit comments

Comments
 (0)