Поделиться через


Manage VPN Connections in Windows 8 by Using Windows PowerShell

 

Applies To: Windows Server 2012 R2, Windows Server 2012

To make virtual private network (VPN) profile management easier for administrators, Windows 8 includes new Windows PowerShell cmdlets 8. These cmdlets help administrators create, configure, and remove VPN connections on client computers by using Windows PowerShell scripts.

Windows PowerShell cmdlets enable you to achieve complex tasks with a few lines of script. Third-party vendors can build custom solutions based on the overall Windows PowerShell support that is provided by Windows, specifically in Windows Networking.

You can write simple Windows PowerShell scripts by using these cmdlets with the required configuration to deploy a VPN, and distribute these scripts to client computers through a common shared resource or a web portal. Knowledge workers then run these single-click scripts on their computers, and the VPN profiles are configured automatically.

Use VPN deployment and management scripts: For IT pros

You can use Windows PowerShell cmdlets to write scripts to deploy VPN connections on computers running Windows 8. The following sections include:

  1. Create VPN connections

  2. Configure and edit VPN connections

  3. Write configuration scripts for VPN connection management

  4. Use Windows PowerShell cmdlets for third-party EAP methods

Create VPN connections

The Windows PowerShell cmdlet for creating a VPN connection on the client system is Add-VpnConnection.

Syntax

Add-VpnConnection [-Name] <string> [-ServerAddress] <string> [-TunnelType <string> {Pptp | L2tp | Sstp | Ikev2 | Automatic}] [-EncryptionLevel <string> {NoEncryption | Optional | Required | Maximum}] [-AuthenticationMethod <string[]> {Pap | Chap | MSChapv2 | Eap}] [-SplitTunneling] [-AllUserConnection] [-L2tpPsk <string>] [-RememberCredential] [-UseWinlogonCredential] [-EapConfigXmlStream <xml>] [-Force] [-PassThru] [-WhatIf] [-Confirm]

Properties

  1. Name is the connection name, which is a mandatory parameter, and it cannot be changed.

  2. ServerAddress is the IP address (FQDN, or URL) of the remote server to which the connection is to be established. This is a mandatory parameter.

  3. The remainder of the properties are optional. Their names and value sets indicate their purpose. For example, TunnelType specifies the VPN tunnel selection (such as PPTP or L2TP), and AuthenticationMethod specifies the VPN authentication protocol selection.

  4. Switch parameters (SplitTunneling, AllUserConnection, RememberCredentials, UseWinlogonCredentials), when specified, enable the property.

  5. EapConfigXmlStream parameter accepts Extensible Authentication Protocol (EAP) configuration XML. This can be any EAP XML (Microsoft or non-Microsoft). For EAP methods in Windows 8, this XML can be generated by using the New-EapConfiguration, which is described later in this document.

Configure and edit VPN connections

The Windows PowerShell cmdlet for editing a VPN connection on the client system is Set-VpnConnection.

Syntax

Set-VpnConnection [-Name] <string> [[-ServerAddress] <string>] [-TunnelType <string> {Pptp | L2tp | Sstp | Ikev2 | Automatic}] [-EncryptionLevel <string> {NoEncryption | Optional | Required | Maximum}] [-AuthenticationMethod <string[]> {Pap | Chap | MSChapv2 | Eap}] [-SplitTunneling <bool>] [-AllUserConnection] [-L2tpPsk <string>] [-RememberCredential <bool>] [-UseWinlogonCredential <bool>] [-EapConfigXmlStream <xml>] [-PassThru] [-Force] [-WhatIf] [-Confirm]

Properties

  1. Name is the connection name. It is a mandatory parameter, and it cannot be modified.

  2. AllUserConnection is used to identify the scope of the connection. If this parameter is supplied, the global address list is searched for the connection; otherwise, the local connections are searched.

  3. All the other parameters carry the same meaning as explained previously in the information about the Add-VpnConnection cmdlet .

New-EapConfiguration

New-EapConfiguration is a VPN connection cmdlet that is used to generate XML for EAP configuration. It can be used with the Add-VpnConnection or Set-VpnConnection cmdlets.

This cmdlet can generate XML for EAP, and it includes the following parameters: EAP-MSCHAPv2 (default configuration), EAP-TLS (for smart card or other certificates), and EAP-TTLS (for internal authentication). It accepts configuration XML from Microsoft or from third-parties for EAP, non-EAP, or PEAP.

Syntax

New-EapConfiguration [[-UseWinlogonCredential]] [-WhatIf] [-Confirm]
New-EapConfiguration [-Tls] [-VerifyServerIdentity] [-UserCertificate] [-WhatIf] [-Confirm]
New-EapConfiguration [-Ttls] [-UseWinlogonCredential] [-TunnledNonEapAuthMethod <string> {Pap | Chap | MSChap | MSChapv2}] [-TunnledEapAuthMethod <xml>] [-WhatIf] [-Confirm]
New-EapConfiguration [-Peap] [-VerifyServerIdentity] [-TunnledEapAuthMethod <xml>] [-EnableNap] [-FastReconnect <bool>] [-WhatIf] [-Confirm]

Properties

  1. If no method switch (Tls, Ttls, or Peap) is supplied, the default Eap-MsChapv2 method is used.

  2. Smart card is the default choice for EAP-TLS. To use user certificates, specify UserCertificate.

  3. In addition to the methods that are provided by Microsoft, administrators can supply configuration XML for any EAP method for the Ttls and Peap parameter sets in the TunneledEapAuthMethod property.

VPN connection lookup

The Windows PowerShell cmdlet for VPN connection lookup on the client system is Get-VpnConnection.

Syntax

Get-VpnConnection [[-Name] <string[]>] [-AllUserConnection]

Properties

  1. Name is the connection name. It is an optional parameter.

    1. If the connection name is not specified, all VPN connections in the given address list are listed for the user.

    2. More than one connection name can also be looked up in the global address list by using a comma-separated list.

  2. AllUserConnection parameter is used to identify the scope of the connection. If this switch is supplied, the global address list is searched for the connections; otherwise, the local connections are used.

VPN connection removal

The Windows PowerShell cmdlet for VPN connection deletion on the client system is Remove-VpnConnection.

Syntax

  1. Name is the connection name. It is a mandatory parameter. More than one connection name can be removed at one time by using a comma-separated list.

  2. AllUserConnection parameter is used to identify the scope of the connection. If this switch is supplied, the connections are removed from the global address list; otherwise, the local connections are removed.

  3. Force switch is specified to suppress the connection removal confirmation dialogue.

Write configuration scripts for VPN connection management

You can use the VPN management cmdlets described previously to deploy VPN connections on computers running Windows 8, according to the network deployment and corporate requirements.When distributed, this script provides a single-click installation for knowledge workers.

The following examples show how to write a single-click script that can distribute the VPN profile and run specific post-connection actions every time the VPN interface initiates.

# VPN Connection ‘My VPN’ provisioning 

#------------------------------------------------------------
# VPN Connection look-up to check any previous installations
#------------------------------------------------------------
$isTestVpn = $false
$vpnConnections = Get-VpnConnection -AllUserConnection

if($vpnConnections.Name -eq "My VPN")
{
    Write-Host "'My VPN' connection is already configured on your system." -ForegroundColor Yellow -BackgroundColor DarkGreen
    Write-Host "If you wish to reinstall, please uninstall the connection and then attemp again." -ForegroundColor Yellow -BackgroundColor DarkGreen
    Write-Host ""
    Write-Host "Please press any key to exit..."
    $x = read-host
    exit
}

Write-Host "******************************************" -ForegroundColor Black -BackgroundColor White
Write-Host "      Installing 'My VPN' connection      " -ForegroundColor Black -BackgroundColor White
Write-Host "__________________________________________" -ForegroundColor Black -BackgroundColor White

try
{
    # Generate Eap-Mschapv2 configuration XML
    $a = New-EapConfiguration
    # Generate Eap-TTLS configuration XML with EAP-Mschapv2 as inner method
    $b = New-EapConfiguration -Ttls -TunnledEapAuthMethod $a.EapConfigXmlStream
    # Edit properties within the generated configuration XML
    $c = $b.EapConfigXmlStream
    $c.EapHostConfig.Config.EapTtls.Phase1Identity.IdentityPrivacy = "false"

    # Create the VPN connection ‘My VPN’ with the EAP configuration XML generated above
    Add-VpnConnection -Name "My VPN" -ServerAddress "contoso.com" -EncryptionLevel Required -AuthenticationMethod Eap -EapConfigXmlStream $c -SplitTunneling -AllUserConnection
}
catch
{
    Write-Host "Error in connection setup!" -ForegroundColor White -BackgroundColor Red
    Write-Host $_.Exception.Message
    throw
}

Write-Host ""
Write-Host "‘My VPN’ VPN connection is ready for use." -ForegroundColor Black -BackgroundColor White

The following sample script adds a new task to the system Task Scheduler. It performs the tasks when the VPN connects and disconnects.

## This piece of code performs the following actions –
## 1. Dynamically generate support files for VPN connection configuration,  
## 2. Creates task in task-scheduler, which triggers post-connect actions on the VPN connection using 
##    the support files generated above

write-host "Generating support files..."
# Create the common directory for support files
$testProfileDir = Test-Path $env:ALLUSERSPROFILE\Microsoft\Network\Connections\Cm\MyVPN\
if(!$testProfileDir)
{
    mkdir $env:ALLUSERSPROFILE\Microsoft\Network\Connections\Cm\MyVPN
}

$Directory = "$env:ALLUSERSPROFILE\Microsoft\Network\Connections\Cm\MyPN"

# Specify support file content variables, and generate these files in the common location ($Directory)
$RoutesFile = $Directory + "\routes.netsh"
$DnsSuffixFile = $Directory + "\dnssuffix.ps1"
$ConnectTaskFile = $Directory + "\Connect.xml"

# route provisioning file content
$routes = @"
interface ipv4
add route prefix=192.168.0.0/16 interface="My VPN" store=active
exit
"@

# Connection specific DNS suffix provisioning file content
$dnssuffix = @"
Set-DnsClient -InterfaceAlias "My VPN" -ConnectionSpecificSuffix "contoso.com"
"@

# Post-connect task scheduler XML file content
$connecttask = @"
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="https://schemas.microsoft.com/windows/2004/02/mit/task">

# XML file content
</Settings>
  <Actions Context="Author">
    <Exec>
      <Command>netsh.exe</Command>
      <Arguments>exec routes.netsh</Arguments>
      <WorkingDirectory>%ALLUSERSPROFILE%\Microsoft\Network\Connections\Cm\MyVPN\</WorkingDirectory>
    </Exec>
    <Exec>
      <Command>powershell.exe</Command>
      <Arguments>-Command "%ALLUSERSPROFILE%\Microsoft\Network\Connections\Cm\MyVPN\dnssuffix.ps1"
      </Arguments>
    </Exec>
  </Actions>
</Task>
"@

$routes|out-file -FilePath $RoutesFile
$dnssuffix|out-file -FilePath $DnsSuffixFile
$connecttask|out-file -FilePath $ConnectTaskFile

write-host "Files generated..."

write-host "Initiating configuration for ‘My VPN' ..." -ForegroundColor Black -BackgroundColor White
SCHTASKS /create /tn "\MyVPN\Connect" /xml $env:ALLUSERSPROFILE\Microsoft\Network\Connections\Cm\MyVPN\Connect.xml /F

write-host ""
write-host "Configuration completed..." -ForegroundColor Black -BackgroundColor White

Use VPN deployment and management scripts: For knowledge workers

After you write the scripts for connection deployment and distribute these scripts to a public shared resource or to an external web portal, knowledge workers can run them by clicking the link you provide. When a user runs the scripts, the VPN profile is configured on the client computer, and it is ready to use on the corporate network.

The Windows PowerShell cmdlets are available in all Windows 8 operating systems, and all types of clients (managed, unmanaged, computers, and tablets) can use these scripts for client deployment.

Use Windows PowerShell cmdlets for third-party EAP methods

Extensible Authentication Protocol (EAP) methods in Windows 8 are supported with the Add-VpnConnection , Set-VpnConnection , and Get-VpnConnection Windows PowerShell cmdlets, but configuration and retrieval of third-party EAP authentication methods for the given VPN connection can be a bit difficult.

If a system is already configured with a VPN connection that uses a third-party EAP method, the Get-VpnConnection cmdlet for that VPN connection might fail if the configuration details are not stored in the default global address list. The following procedure describes how to retrieve the EAP configuration settings for third-party EAP methods and use those settings to set up similar new VPN connections.

To use third-party EAP settings

  1. On a computer where the third-party EAP method is configured for VPN, click Start, type Control Panel, click Network and Internet, and then click Network Connections.

  2. Right-click the VPN connection that is configured with third-party EAP, and select Properties.

  3. In the VPN Connection Properties, click the Security tab.

  4. In Authentication - Use Extensible Authentication Protocol (EAP), verify that the third-party EAP method is selected.

  5. Click Properties under the EAP method drop-down list.

  6. Click OK twice to exit.

  7. The third-party EAP configuration details will now be stored in the default global address list, and the subsequent calls to Get-VpnConnection will succeed.

    To configure new VPN connections with the identical third-party EAP settings, retrieve the EAP configuration XML by using Get-VpnConnection as described previously, and then use Add/Set-VpnConnection with the EAP XML.