Skip to content

Instantly share code, notes, and snippets.

@tkuennen
Last active May 30, 2022 10:45
Show Gist options
  • Save tkuennen/24e7c5215b0ff982b9aec82a376b314a to your computer and use it in GitHub Desktop.
Save tkuennen/24e7c5215b0ff982b9aec82a376b314a to your computer and use it in GitHub Desktop.

A script to add a VPN connection in Windows 10

  1. Download both of the scripts, and place both files on the desktop.
  2. Double click on the VPN.bat file
  3. When prompted click "Yes" to run the script as an administrative user
  4. Enter the connection details when prompted (VPN address, pre shared key)
  5. Reboot
@ECHO OFF
PowerShell.exe -ExecutionPolicy Bypass -Command "& '~\Desktop\z-ms-l2tp-ipsec.ps1'"
PAUSE
#>
<#
.SYNOPSIS
This script adds an L2TP over IPsec VPN while asking for name, gateway IP address, and pre shared key.
Version: 1.0.4
.DESCRIPTION
With this Powershell Script the addition of an L2TP over IPsec VPN can be automated
#>
#checks if powershell is in Administrator mode, if not powershell will fix it
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
$arguments = "& '" + $myinvocation.mycommand.definition + "'"
Start-Process powershell -Verb runAs -ArgumentList $arguments
Break
}
# General settings
$VpnName = Read-host -Prompt "Whats the name of the VPN Connection?"
$gateway = Read-Host -Prompt "Whats the gateway of the VPN Connection"
write-host "$vpnname " -f yellow -NoNewline ; write-host "is the name of the connection and gateway" -NoNewline ; write-host " $gateway." -f Yellow
$psk = Read-Host -Prompt "Enter preshared key for the VPN"
$regp = 'HKLM:\SYSTEM\CurrentControlSet\Services\PolicyAgent' #if VPN server is behind NAT, otherwise comment out this line.
# UDP encapsulation
REG ADD HKLM\SYSTEM\CurrentControlSet\Services\PolicyAgent /v AssumeUDPEncapsulationContextOnSendRule /t REG_DWORD /d 0x2 /f
# Add l2tp vpn
Add-VpnConnection -Name $VpnName -ServerAddress $gateway -TunnelType L2tp -AuthenticationMethod MSChapv2 -EncryptionLevel Required -L2tpPsk $psk -Force `
-AllUserConnection -UseWinLogonCredential $false -SplitTunneling
Write-Host "Connection has been added." -f Green
# Add registry value, if VPN server is behind NAT. Otherwise comment out this line.
New-ItemProperty -Path $regp -Name AssumeUDPEncapsulationContextOnSendRule -Value 2 -PropertyType 'DWORD' -Force
$confirm = Read-Host -Prompt '... L2Tp over IPsec is added. System needs to be restarted before the VPN connection can work. Reboot system? Y/N ...'
If (($confirm -eq "Y")) {
Restart-Computer
}
else {
$cp = Read-Host -Prompt "Ok. Closing Powershell? Y/N"
if (($cp -eq "Y")) {
ncpa.cpl
Get-Process powershell | Stop-Process
}
else {
ncpa.cpl
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment