Script to configure VPN on Power Shell

Remote work in companies is becoming more common in recent years. System administrators need to organize a VPN connection to the company network on users’ home computers. The setup time takes from 10 minutes, and if everything goes smoothly, the user will figure out how to download Any Desk or some other client for a remote connection, then the fact of a stable Internet plays a role, and of course, setting up the VPN connection itself – we drive in the address, encryption method, login , password, key.

What if there are 10 or more users? This already needs to be spent more time, but what if they all need to urgently set everything up in the morning? After a little thought, I decided to write a fairly simple, but at the same time useful Power Shell script and then packaged it into an .exe file.

Please do not judge strictly, I hope the material is useful to someone.

The process of creating a script with comments:

Elevate privileges to administrator:

if (!(net session)) {$path =  "& '" + $myinvocation.mycommand.definition + "'" ; Start-Process powershell -Verb runAs -ArgumentList $path ; exit}

Allow script execution:

Set-ExecutionPolicy Unrestricted -Force

Set variables for VPN connection:

# Имя подключения
$VPNconnectionSSTP = "VPN_SSTP"
$VPNconnectionL2TP = "VPN_L2TP"

# тип подключения       
$VPNtypeSSTP = "sstp"                           
$VPNtypeL2TP ="l2tp"

# ip адрес или доменное имя                           
$SRVaddressSSTP = "ip_addr"
$SRVaddressL2TP = "ip_addr"

# DNS суффикс
$dnssuf = "domain.local"

# ключ l2tp
$l2tp_key = "ключ"

# метод аутентификации
$auth_method = "MSChapv2"

# сертификат .cer открываем через блокнот и копируем от начала до конца
$vpn_cert = "-----BEGIN CERTIFICATE-----
сам сертификат (скопировать содержимое открыв его через текстовый редактор)
-----END CERTIFICATE-----"

We save the certificate in the user directory:

$vpn_cert | Out-File -FilePath "$env:HOMEPATH\vpn_cert.cer" -Encoding utf8

Create SSTP connections SSTP and L2TP respectively:

Add-VpnConnection -Name $VPNconnectionSSTP -ServerAddress $SRVaddressSSTP -TunnelType $VPNtypeSSTP -AuthenticationMethod $auth_method -EncryptionLevel "Optional" -DnsSuffix $dnssuf -SplitTunneling -IdleDisconnectSeconds 900 -RememberCredential

Add-VpnConnection -Name $VPNconnectionL2TP -ServerAddress $SRVaddressL2TP -TunnelType $VPNtypeL2TP -AuthenticationMethod $auth_method -L2tpPsk $l2tp_key -EncryptionLevel "Optional" -DnsSuffix $dnssuf  -SplitTunneling -IdleDisconnectSeconds 900 -RememberCredential

Install the certificate to the user’s trusted root certificates:

certutil -f -addstore root "$env:HOMEPATH\vpn_cert.cer"

Everybody! The script is ready. Save it with .PS1 extension

We can also make an EXE file out of it for convenience.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *