Skip to content

Instantly share code, notes, and snippets.

@uyriq
Last active June 20, 2024 17:40
Show Gist options
  • Save uyriq/bea94963409c17c7aab60134b895b5ae to your computer and use it in GitHub Desktop.
Save uyriq/bea94963409c17c7aab60134b895b5ae to your computer and use it in GitHub Desktop.
The `Get-VPNConnectionInfo ` function checks if the current internet connection is made through one of the known VPN providers. It fetches the current IP information from ipapi.co and compares the organization name (org field) against a predefined list of VPN providers.
function Get-VPNConnectionInfo {
$connectedVPN = $false
try {
# Read the list of known VPN providers from a JSON file
if (Test-Path -Path "./knownVPNproviders.json") {
$knownVPNProviders = Get-Content -Path "./knownVPNproviders.json" | ConvertFrom-Json
}
else {
Write-Warning "Warning: The file 'knownVPNproviders.json' was not found."
$knownVPNProviders = @()
}
}
catch {
Write-Host "Error occurred while fetching VPN connection information: $($_.Exception.Message)" -ForegroundColor Red
}
try {
$connect_info = (Invoke-WebRequest -UseBasicParsing -ErrorAction SilentlyContinue 'https://ipapi.co/json').Content | ConvertFrom-Json
# Convert to PSCustomObject to ensure properties can be added
$connect_info = [PSCustomObject]$connect_info
# Add field to store VPN name
if (-not $connect_info.psobject.Properties.Match('vpnName').Count) {
Add-Member -InputObject $connect_info -MemberType NoteProperty -Name vpnName -Value ""
}
# If $connect_info.org contains substring VPN in it, set $connect_info.vpnName or leave ""
if ($connect_info.org -match "VPN") {
$connect_info.vpnName = $connect_info.org
$connectedVPN = $true
}
else {
$connect_info.vpnName = "Not connected to any known VPN " # Empty by default
}
if ($connect_info.org -in $knownVPNProviders) {
$connectedVPN = $true
$connect_info.vpnName = $connect_info.org
}
if ([IPAddress]::TryParse($connect_info.ip, [ref]$null)) {
$connect_info = @{
ip = $connect_info.ip
city = $connect_info.city
country = $connect_info.country
org = $connect_info.org
vpnName = $connect_info.vpnName
}
}
$vpnConnectionInfo = [PSCustomObject]@{
connectedVPN = $connectedVPN
connect_info = $connect_info
}
return $vpnConnectionInfo
}
catch {
Write-Host "Error occurred while fetching VPN connection information: $($_.Exception.Message)" -ForegroundColor Red
return $connectedVPN
}
}
["VPNProvider1", "VPNProvider2", "other_provider_name_taken_from_org_field"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment