Skip to content

Instantly share code, notes, and snippets.

@Vladkarok
Created February 27, 2023 16:41
Show Gist options
  • Save Vladkarok/da647b3009f48cb6eb08ce572ba81cba to your computer and use it in GitHub Desktop.
Save Vladkarok/da647b3009f48cb6eb08ce572ba81cba to your computer and use it in GitHub Desktop.
Powershell add VPN IKEv2 with LE certificates for Windows 10/11
# This script will download LE intermediate CA and install it in a computer,
# create IKEv2 vpn connection with SplitTunneling, -DnsSuffix and -RememberCredential
# USAGE
# Open Powershell as administarton and run next line:
# PowerShell.exe -ExecutionPolicy Bypass -File .\addvpn.ps1
# where "addvpn.ps1" is the name of this script
# Define the parameters for the VPN connection (change it)
$Name = "NAME_OF_VPN_CONNECTION"
$ServerAddress = "SERVER_ADDRESS"
$DnsSuffix = "DNS_SUFFIX"
# Define the certificate URL
$CertificateUrl = "https://letsencrypt.org/certs/lets-encrypt-r3.der"
$BaseDir = Join-Path $home "Downloads"
$CertName = $CertificateUrl.Substring($CertificateUrl.LastIndexOf("/") + 1)
$OutFile = Join-Path $BaseDir $CertName
Write-Host "Creating VPN connection with name '$Name', server address '$ServerAddress', and DNS suffix '$DnsSuffix'"
Write-Host "Downloading certificate from '$CertificateUrl' to '$OutFile'"
# Check if the certificate file already exists
if (!(Test-Path $OutFile)) {
# Downloads certificate
try {
Invoke-WebRequest -Uri $CertificateUrl -OutFile $OutFile
} catch {
Write-Host $_.Exception | format-list -force
}
}
# Install certificate
Write-Host "Installing certificate from '$OutFile'"
try {
Import-Certificate -FilePath $OutFile -CertStoreLocation Cert:\LocalMachine\CA
Write-Host "Successfully installed certificate"
# Delete the certificate file
Write-Host "Deleting downloaded certificate file '$OutFile'"
Remove-Item $OutFile
} catch {
Write-Error "Failed to install certificate: $_"
exit 1
}
# Create a VPN connection
try {
Add-VpnConnection -Name $Name -ServerAddress $ServerAddress -TunnelType Ikev2 -RememberCredential -SplitTunneling -DnsSuffix $DnsSuffix -EncryptionLevel "Required" -PassThru
} catch {
Write-Error "Failed to create VPN connection: $_"
exit 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment