Description

This script adding L2TP over IPsec VPN. 

Changelog

1.0.3 - Edit script formatting.
1.0.2 - Removed Set-ExecutionPolicy cmdlet notice, since everyone has this knowledge already.
1.0.1 - Adds Administrator mode check.

Development Information

This is my first contribution to the Microsoft Script Center. A lot of scripters from this website have been helped me very well in the past by the scripts they have vreated and posted here. Many thanks! This script is therefore my first powerhell script.

You can find the Dutch explanation on this page: WindowsTechBlog.nl.

Requirement: Windows 8, Windows 10, Windows Server 2012, Windows Server 2012 R2 or Windows Server 2016 .

Code

 

PowerShell
Edit|Remove
#>  
  <# 
  .SYNOPSIS 
    This script adding L2TP over IPsec VPN. 
    Version: 1.0.3   
  .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.   
   
#add l2tp vpn   
Add-VpnConnection -Name $VpnName -ServerAddress $gateway -TunnelType L2tp -AuthenticationMethod MSChapv2 -EncryptionLevel Optional -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  
    }  
}