{"id":208179,"date":"2024-01-29T09:07:26","date_gmt":"2024-01-29T09:07:26","guid":{"rendered":"https:\/\/www.ninjaone.com\/script-hub\/configurare-una-vpn-windows-con-powershell\/"},"modified":"2024-03-13T19:54:36","modified_gmt":"2024-03-13T19:54:36","slug":"configurare-una-vpn-windows-con-powershell","status":"publish","type":"script_hub","link":"https:\/\/www.ninjaone.com\/it\/script-hub\/configurare-una-vpn-windows-con-powershell\/","title":{"rendered":"Semplificare l\u2019impostazione della VPN: Configurare una VPN con PowerShell"},"content":{"rendered":"<h2>Punti chiave<\/h2>\n<ul>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"1\" data-aria-level=\"1\"><strong>Configurare una VPN in modo automatico<\/strong>: Lo script automatizza la creazione di connessioni VPN in Windows, migliorando l&#8217;efficienza.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"2\" data-aria-level=\"1\"><strong>Supporta diversi tipi di VPN<\/strong>: Compatibile con L2TP, SSTP, IKEV2 e seleziona automaticamente i tipi di VPN.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"3\" data-aria-level=\"1\"><strong>Flessibilit\u00e0 nella configurazione<\/strong>: Pu\u00f2 estrarre le impostazioni VPN dalla documentazione NinjaOne o da campi personalizzati per configurazioni su misura.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"4\" data-aria-level=\"1\"><strong>Sicurezza migliorata<\/strong>: Standardizza le configurazioni VPN tra i dispositivi, riducendo il rischio di configurazioni errate.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"5\" data-aria-level=\"1\"><strong>Gestione dei collegamenti e delle icone<\/strong>: Crea automaticamente i collegamenti al desktop e gestisce le icone dei collegamenti VPN.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"6\" data-aria-level=\"1\"><strong>Modifiche del registro di Windows<\/strong>: Adatta le impostazioni come l&#8217;incapsulamento UDP nel registro di Windows alle esigenze specifiche della VPN.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"7\" data-aria-level=\"1\"><strong>Capacit\u00e0 di sovrascrittura<\/strong>: Offre l&#8217;opzione di sovrascrivere le connessioni VPN esistenti con lo stesso nome.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"8\" data-aria-level=\"1\"><strong>Testa prima di un utilizzo diffuso<\/strong>: Si consiglia di testare lo script in un ambiente controllato prima dell&#8217;applicazione su larga scala.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"9\" data-aria-level=\"1\"><strong>Sono necessari aggiornamenti regolari<\/strong>: \u00c8 necessario aggiornare lo script per garantire la compatibilit\u00e0 con gli ultimi standard VPN e gli aggiornamenti di Windows.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"10\" data-aria-level=\"1\"><strong>Gestione sicura degli script<\/strong>: \u00c8 importante memorizzare lo script e le sue credenziali in modo sicuro per evitare accessi non autorizzati.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"11\" data-aria-level=\"1\"><strong>Integrazione con NinjaOne<\/strong>: Lo script integra la piattaforma NinjaOne, semplificando la gestione delle VPN nelle infrastrutture IT.<\/li>\n<\/ul>\n<p>L&#8217;integrazione delle <a href=\"https:\/\/www.ninjaone.com\/it\/blog\/cos-e-una-rete-privata-virtuale-vpn\/\">reti private virtuali (VPN)<\/a> in ambienti aziendali e IT \u00e8 essenziale per mantenere un accesso sicuro e remoto alle risorse dell&#8217;organizzazione. Con la crescente adozione da parte delle aziende di policy per il lavoro da remoto e di servizi basati sul cloud, la capacit\u00e0 di configurare in modo rapido e sicuro le connessioni VPN diventa fondamentale. In questo senso, gli script di automazione per configurare una VPN giocano un ruolo fondamentale.<\/p>\n<h2>Background<\/h2>\n<p>Lo script PowerShell fornito \u00e8 stato progettato per automatizzare il processo di configurazione di una connessione VPN in ambienti Windows. Si rivolge ai professionisti IT e ai <a href=\"https:\/\/www.ninjaone.com\/what-is-an-msp\/\">fornitori di servizi gestiti (MSP)<\/a> che configurano regolarmente VPN su numerosi dispositivi. Questo script per configurare una VPN non solo fa risparmiare tempo, ma garantisce anche la coerenza e riduce la probabilit\u00e0 di errori manuali nelle configurazioni VPN.<\/p>\n<h2>Lo script per configurare una VPN:<\/h2>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\">#Requires -Version 5.1\r\n\r\n&lt;#\r\n.SYNOPSIS\r\n    Creates a VPN using the built-in Windows VPN client, with configuration options from Ninja Documentation or Device Custom Fields.\r\n.DESCRIPTION\r\n    This script will create a VPN using the built-in Windows VPN client. It will not create PPTP or \"No Encryption\" VPNs. \r\n    It can pull all the necessary VPN information from a Ninja Document or custom field you specify. \r\n    You can override the Documentation fields with parameters or only use parameters if you would like.\r\n\r\n    For more information on Ninja Documentation: https:\/\/ninjarmm.zendesk.com\/hc\/en-us\/articles\/360061218431-Documentation\r\n\r\nOPTIONAL: Custom Fields - All Fields must be readable by scripts\r\n    # Name # - # Field Type and what values to use for dropdowns. #\r\n    vpnName - text field\r\n    vpnHost - text field\r\n    presharedKey - Secure field (if using device custom fields) or text field.\r\n    tunnelType - dropdown field. Acceptable values are L2TP, SSTP, IKEV2, Automatic\r\n    authMethod - multi-select field. Acceptable values are PAP, Chap, MSChapv2, MachineCertificate\r\n    encryptionLevel - dropdown field. Acceptable values are Optional, Required, Maximum\r\n    dnsSuffix - text field\r\n    rememberCreds - Checkbox\r\n    useWinCredentials - Checkbox\r\n    assumeUdpEncapsulation - Checkbox\r\n    splitTunneling - Checkbox\r\n    createVpnShortcut - Checkbox\r\n    shortcutUrl - URL or Text\r\n    shortcutIconDirectory - Text\r\n\r\nPARAMETER: -DocumentName \"ReplaceWithNameOfyourNinjaDocument\"\r\n    Replace the value in quotes with the document you'd like to retireve the vpn parameters from (if any).\r\n\r\nPARAMETER: -Name \"Contoso VPN\"\r\n    The name of the VPN you would like to create\r\n\r\nPARAMETER: -Server \"replace.me\"\r\n    The endpoint\/server the VPN will try to establish a connection with.\r\n\r\nPARAMETER: -PreSharedKey \"ReplaceWithPreSharedKey\"\r\n    The Pre-Shared Key for the VPN.\r\n\r\nPARAMETER: -TunnelType \"L2TP\"\r\n    The Type of VPN ex. L2TP, SSTP, IKEV2, Automatic\r\n\r\nPARAMETER: -AuthMethod \"PAP,CHAP\"\r\n    The authentication methods supported by the VPN separated by commas.\r\n\r\nPARAMETER: -EncryptionLevel \"Required\"\r\n    The Encryption level used by the VPN.\r\n\r\nPARAMETER: -DNSSuffix \"contoso.local\"\r\n    The DNS Suffix used by the connection.\r\n\r\nPARAMETER: -RememberCreds\r\n    Whether or not the VPN should remember the previously used credentials for future connections.\r\n\r\nPARAMETER: -UseWinlogonCredential\r\n    Whether or not the VPN should use the Windows logon credentials for authentication.\r\n\r\nPARAMETER: -AssumeUDPEncapsulation\r\n    Sets the AssumeUDPEncapsulation registry key which is required by many VPNs\r\n.LINK\r\n    https:\/\/learn.microsoft.com\/en-us\/troubleshoot\/windows-server\/networking\/configure-l2tp-ipsec-server-behind-nat-t-device\r\n\r\nPARAMETER: -SplitTunneling\r\n    Enables split tunneling.\r\n\r\nPARAMETER: -CreateShortcut\r\n    Creates a desktop shortcut for accessing the VPN.\r\n\r\nPARAMETER: -URL\r\n   A URL to an image you'd like to download and use for the shortcut icon. Icon will be stored at -IconDirectory.\r\n\r\nPARAMETER: -IconDirectory \"C:ReplaceMe\"\r\n    The directory where the shortcut's icon file will be stored.\r\n\r\nPRESET PARAMETER: -SkipSleep\r\n    By default the script sleeps for a random interval between 3 and 60 seconds prior to downloading an icon (if the script is given a url). This parameter skips the sleep.\r\n\r\nPARAMETER: -Overwrite\r\n    Overwrites an existing VPN with the same name, if present.\r\n.OUTPUTS\r\n    None\r\n.NOTES\r\n    Minimum Supported OS: Windows 10\r\n    Release Notes: Script renamed, Script Variable support enhanced, improved icon handling.\r\nBy using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https:\/\/www.ninjaone.com\/terms-of-use.\r\n    Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. \r\n    Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. \r\n    Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. \r\n    Warranty Disclaimer: The script is provided \u201cas is\u201d and \u201cas available\u201d, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. \r\n    Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. \r\n    Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. \r\n    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).\r\n#&gt;\r\n\r\n[CmdletBinding()]\r\nparam (\r\n    [Parameter()]\r\n    [String]$DocumentName,\r\n    [Parameter()]\r\n    [String]$Name,\r\n    [Parameter()]\r\n    [String]$NameField = \"vpnName\",\r\n    [Parameter()]\r\n    [String]$Server,\r\n    [Parameter()]\r\n    [String]$ServerField = \"vpnHost\",\r\n    [Parameter()]\r\n    [String]$PreSharedKey,\r\n    [Parameter()]\r\n    [String]$PreSharedKeyField = \"presharedKey\",\r\n    [Parameter()]\r\n    [String]$TunnelType = \"Automatic\",\r\n    [Parameter()]\r\n    [String]$TunnelTypeField = \"tunnelType\",\r\n    [Parameter()]\r\n    [String[]]$AuthMethod,\r\n    [Parameter()]\r\n    [String]$AuthMethodField = \"authMethod\",\r\n    [Parameter()]\r\n    [String]$EncryptionLevel,\r\n    [Parameter()]\r\n    [String]$EncryptionLevelField = \"encryptionLevel\",\r\n    [Parameter()]\r\n    [String]$DNSSuffix,\r\n    [Parameter()]\r\n    [String]$DNSSuffixField = \"dnsSuffix\",\r\n    [Parameter()]\r\n    [Switch]$RememberCreds = [System.Convert]::ToBoolean($env:rememberUserCredentials),\r\n    [Parameter()]\r\n    [String]$RememberCredsField = \"rememberCreds\",\r\n    [Parameter()]\r\n    [Switch]$UseWinlogonCredential = [System.Convert]::ToBoolean($env:useWindowsCredentials),\r\n    [Parameter()]\r\n    [String]$UseWinlogonCredsField = \"useWinCredentials\",\r\n    [Parameter()]\r\n    [Switch]$AssumeUDPencapsulation = [System.Convert]::ToBoolean($env:assumeUdpEncapsulation),\r\n    [Parameter()]\r\n    [String]$UDPField = \"assumeUdpEncapsulation\",\r\n    [Parameter()]\r\n    [Switch]$SplitTunneling = [System.Convert]::ToBoolean($env:splitTunneling),\r\n    [Parameter()]\r\n    [String]$SplitTunnelingField = \"splitTunneling\",\r\n    [Parameter()]\r\n    [Switch]$CreateShortcut = [System.Convert]::ToBoolean($env:createVpnDesktopShortcut),\r\n    [Parameter()]\r\n    [String]$ShortcutField = \"createVpnShortcut\",\r\n    [Parameter()]\r\n    [String]$Url,\r\n    [Parameter()]\r\n    [String]$UrlField = \"shortcutUrl\",\r\n    [Parameter()]\r\n    [String]$IconDirectory,\r\n    [Parameter()]\r\n    [String]$IconDirectoryField = \"shortcutIconDirectory\",\r\n    [Parameter()]\r\n    [Switch]$Overwrite = [System.Convert]::ToBoolean($env:overwrite),\r\n    [Parameter()]\r\n    [Switch]$SkipSleep\r\n)\r\nbegin {\r\n    Add-Type -AssemblyName System.Drawing\r\n\r\n    if ([System.Convert]::ToBoolean($env:verboseOutput)) {\r\n        $VerbosePreference = 'Continue'\r\n    }\r\n\r\n    # You can replace the line below with $IconBase64 = 'ReplaceThisWithYourBase64EncodedImageEncasedInQuotes', and the script will decode the image and use it for the VPN shortcut.\r\n    $IconBase64 = 'iVBORw0KGgoAAAANSUhEUgAAAEAAAABABAMAAABYR2ztAAAAElBMVEUAAAD\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/8+Uq06AAAABXRSTlMAAECAv9KsvScAAAEsSURBVEjH7ZUxDsIwDEWtFA7ADbqwM8COhLpXtLn\/VbDzXduFRpEYEEOzRP15+ontL5VOjUU78DuAiK45P3hLOT+Jzjn3rhXglnlNhDNQpglwyGXdYQED0wQY8DHDAgamMdDx3qdhsVgMoF0YOBYpmYUaQBsZuBVJjmABA9UmBgY5gKtobiDazIB+JC0kGIhWgPJBWkgwEG0N2GUwMMCugIUb4Ap75IxCggEeaWVOUrcaHEKZ1qiRhV4NhtAoa\/WF0lMNutjqOCx7QRxWGLeXsBq3ByaUEANj8Vr1IEbOV+iBrjcAJdQB7cG9CqCJy1A\/ga4YHKVl20Bo+jbgY6sAPvgK4NGpAuv9G6BxRfORzTKbjQrprA\/L01kZt6dzMzAhndtASKcD+\/\/iX4AX3T+7h6Wwmo8AAAAASUVORK5CYII='\r\n    function Test-IsSystem {\r\n        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()\r\n        return $id.Name -like \"NT AUTHORITY*\" -or $id.IsSystem\r\n    }\r\n\r\n    function Test-IsElevated {\r\n        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()\r\n        $p = New-Object System.Security.Principal.WindowsPrincipal($id)\r\n        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)\r\n    }\r\n\r\n    function ConvertFrom-Base64 {\r\n        param(\r\n            $Base64,\r\n            $Path\r\n        )\r\n        $bytes = [Convert]::FromBase64String($Base64)\r\n\r\n        # This section of code will error out when run multiple times in the same session. This is due to something holding onto the file after closing. \r\n        # The file is unlocked when the PowerShell session is closed.\r\n        $ErrorActionPreference = [System.Management.Automation.ActionPreference]::SilentlyContinue\r\n        [IO.File]::WriteAllBytes($Path, $bytes)\r\n        $ErrorActionPreference = [System.Management.Automation.ActionPreference]::Continue\r\n    }\r\n\r\n    # There are many ways to create icon files. The method below creates a PNG and then creates an ICO file in binary form by creating the header and adding the PNG's binary at the bottom.\r\n    # Once this has been done, we can simply write all the bytes to our new file.\r\n    function ConvertFrom-Image {\r\n        param(\r\n            $ImagePath,\r\n            $Path\r\n        )\r\n\r\n        # Grab an instance of the image and a blank bitmap\r\n        $image = [Drawing.Image]::FromFile($ImagePath)\r\n\r\n        # If you want transparency, you'll need an Alpha channel in the pixel format\r\n        $bitmap = New-Object System.Drawing.Bitmap (255, 255, [system.drawing.imaging.PixelFormat]::Format32bppArgb)\r\n        $bitmap.SetResolution(255, 255)\r\n\r\n        # Create a graphics object which will be used to resize the image to 255px by 255px\r\n        $graphics = [System.Drawing.Graphics]::FromImage($bitmap)\r\n\r\n        # Set some quality settings for the resize operation\r\n        $graphics.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::HighQuality\r\n        $graphics.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic\r\n        $graphics.PixelOffsetMode = [System.Drawing.Drawing2D.PixelOffsetMode]::HighQuality\r\n\r\n        # Draw the image onto the bitmap\r\n        $graphics.DrawImage($Image, 0, 0, 255, 255)\r\n        \r\n        # Temporarily save the image as a PNG\r\n        $RandomNumber = Get-Random -Maximum 1000000\r\n        $bitmap.Save(\"$env:TEMPimage-$RandomNumber.png\", [System.Drawing.Imaging.ImageFormat]::Png)\r\n        $png = \"$env:TEMPimage-$RandomNumber.png\"\r\n\r\n        # Begin building the ICO file in binary using the PNG file (ICO files are comprised of PNG(s))\r\n        if ($PSVersionTable.PSVersion.Major -gt 5) {\r\n            $pngBytes = Get-Content -Path $png -AsByteStream\r\n        }\r\n        else {\r\n            $pngBytes = Get-Content -Path $png -Encoding Byte -Raw\r\n        }\r\n        $icoHeader = [byte[]] @(0, 0, 1, 0, 1, 0)\r\n        $imageDataSize = $pngBytes.Length\r\n        $icoDirectory = [byte[]] @(\r\n            255, 255, # icon size\r\n            0, 0, # color count\r\n            0, 0, # reserved\r\n            0, 0, # hotspot x, hotspot y\r\n            ($imageDataSize -band 0xFF),\r\n            (($imageDataSize -shr 8) -band 0xFF),\r\n            (($imageDataSize -shr 16) -band 0xFF),\r\n            (($imageDataSize -shr 24) -band 0xFF),\r\n            22, 0, 0, 0  # offset to image data\r\n        )\r\n        $iconData = $icoHeader + $icoDirectory + $pngBytes\r\n\r\n        # Once complete, save the icon file\r\n        if (Test-Path $Path -ErrorAction SilentlyContinue) { Remove-Item $Path -Force }\r\n        [System.IO.File]::WriteAllBytes($Path, $iconData)\r\n\r\n        # Close out of everything and remove the temporary file\r\n        if (Test-Path $png -ErrorAction SilentlyContinue) { Remove-Item $png -Force }\r\n        $bitmap.Dispose()\r\n        $image.Dispose()\r\n        $graphics.Dispose()\r\n        [System.GC]::Collect()\r\n\r\n        # Refresh the icon cache\r\n        if ([System.Environment]::OSVersion.Version.Major -ge 10) {\r\n            Invoke-Command { ie4uinit.exe -show }\r\n        }\r\n        else {\r\n            Invoke-Command { ie4uinit.exe -ClearIconCache }\r\n        }\r\n    }\r\n\r\n    # Utility function for downloading files.\r\n    function Invoke-Download {\r\n        param(\r\n            [Parameter()]\r\n            [String]$URL,\r\n            [Parameter()]\r\n            [String]$Path,\r\n            [Parameter()]\r\n            [int]$Attempts = 3,\r\n            [Parameter()]\r\n            [Switch]$SkipSleep\r\n        )\r\n        Write-Host \"URL given, downloading the file...\"\r\n\r\n        $SupportedTLSversions = [enum]::GetValues('Net.SecurityProtocolType')\r\n        if ( ($SupportedTLSversions -contains 'Tls13') -and ($SupportedTLSversions -contains 'Tls12') ) {\r\n            [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol::Tls13 -bor [System.Net.SecurityProtocolType]::Tls12\r\n        }\r\n        elseif ( $SupportedTLSversions -contains 'Tls12' ) {\r\n            [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12\r\n        }\r\n        else {\r\n            # Not everything requires TLS 1.2, but we'll try anyways.\r\n            Write-Warning \"TLS 1.2 and or TLS 1.3 isn't supported on this system. This download may fail!\"\r\n            if ($PSVersionTable.PSVersion.Major -lt 3) {\r\n                Write-Warning \"PowerShell 2 \/ .NET 2.0 doesn't support TLS 1.2.\"\r\n            }\r\n        }\r\n\r\n        $i = 1\r\n        While ($i -le $Attempts) {\r\n            # Some cloud services have rate limiting.\r\n            if (-not ($SkipSleep)) {\r\n                $SleepTime = Get-Random -Minimum 3 -Maximum 15\r\n                Write-Host \"Waiting for $SleepTime seconds.\"\r\n                Start-Sleep -Seconds $SleepTime\r\n            }\r\n            if ($i -ne 1) { Write-Host \"\" }\r\n            Write-Host \"Download Attempt $i\"\r\n\r\n            try {\r\n                # Invoke-WebRequest is preferred because it supports links that redirect, e.g., https:\/\/t.ly.\r\n                if ($PSVersionTable.PSVersion.Major -lt 4) {\r\n                    # Downloads the file\r\n                    $WebClient = New-Object System.Net.WebClient\r\n                    $WebClient.DownloadFile($URL, $Path)\r\n                }\r\n                else {\r\n                    # Standard options for Invoke-WebRequest.\r\n                    $WebRequestArgs = @{\r\n                        Uri                = $URL\r\n                        OutFile            = $Path\r\n                        MaximumRedirection = 10\r\n                        UseBasicParsing    = $true\r\n                    }\r\n\r\n                    # Downloads the file\r\n                    Invoke-WebRequest @WebRequestArgs\r\n                }\r\n\r\n                $File = Test-Path -Path $Path -ErrorAction SilentlyContinue\r\n            }\r\n            catch {\r\n                Write-Warning \"An error has occurred while downloading!\"\r\n                Write-Warning $_.Exception.Message\r\n\r\n                if (Test-Path -Path $Path -ErrorAction SilentlyContinue) {\r\n                    Remove-Item $Path -Force -Confirm:$false -ErrorAction SilentlyContinue\r\n                }\r\n\r\n                $File = $False\r\n            }\r\n\r\n            if ($File) {\r\n                $i = $Attempts\r\n            }\r\n            else {\r\n                Write-Warning \"File failed to download.\"\r\n                Write-Host \"\"\r\n            }\r\n\r\n            $i++\r\n        }\r\n\r\n        if (-not (Test-Path $Path)) {\r\n            Write-Warning \"Failed to download file!\"\r\n        }\r\n        else {\r\n            return $Path\r\n        }\r\n    }\r\n\r\n    # Used for creating desktop shortcuts.\r\n    function New-Shortcut {\r\n        [CmdletBinding()]\r\n        param(\r\n            [Parameter()]\r\n            [String]$Arguments,\r\n            [Parameter()]\r\n            [String]$IconPath,\r\n            [Parameter(ValueFromPipeline)]\r\n            [String]$Path,\r\n            [Parameter()]\r\n            [String]$Target,\r\n            [Parameter()]\r\n            [String]$WorkingDir\r\n        )\r\n        process {\r\n            Write-Host \"Creating shortcut at $Path\"\r\n            $ShellObject = New-Object -ComObject (\"WScript.Shell\")\r\n            $Shortcut = $ShellObject.CreateShortcut($Path)\r\n            $Shortcut.TargetPath = $Target\r\n            if ($WorkingDir) { $Shortcut.WorkingDirectory = $WorkingDir }\r\n            if ($Arguments) { $ShortCut.Arguments = $Arguments }\r\n            if ($IconPath) { $Shortcut.IconLocation = $IconPath }\r\n            $Shortcut.Save()\r\n\r\n            if (-not(Test-Path $Path -ErrorAction Ignore)) {\r\n                Write-Error \"Unable to create shortcut at $Path\"\r\n                exit 1\r\n            }\r\n        }\r\n    }\r\n\r\n    function Set-HKProperty {\r\n        param (\r\n            $Path,\r\n            $Name,\r\n            $Value,\r\n            [ValidateSet('DWord', 'QWord', 'String', 'ExpandedString', 'Binary', 'MultiString', 'Unknown')]\r\n            $PropertyType = 'DWord'\r\n        )\r\n        if (-not $(Test-Path -Path $Path)) {\r\n            # Check if the path does not exist and create the path.\r\n            New-Item -Path $Path -Force | Out-Null\r\n        }\r\n        if ((Get-ItemProperty -Path $Path -Name $Name -ErrorAction Ignore)) {\r\n            # Update the property and print out what it was changed from and what it was changed to.\r\n            $CurrentValue = (Get-ItemProperty -Path $Path -Name $Name -ErrorAction Ignore).$Name\r\n            try {\r\n                Set-ItemProperty -Path $Path -Name $Name -Value $Value -Force -Confirm:$false -ErrorAction Stop | Out-Null\r\n            }\r\n            catch {\r\n                Write-Error \"[Error] Unable to Set registry key for $Name; please see below error!\"\r\n                Write-Error $_\r\n                exit 1\r\n            }\r\n            Write-Host \"$Path$Name changed from $CurrentValue to $($(Get-ItemProperty -Path $Path -Name $Name -ErrorAction Ignore).$Name)\"\r\n        }\r\n        else {\r\n            # Create the property with a value.\r\n            try {\r\n                New-ItemProperty -Path $Path -Name $Name -Value $Value -PropertyType $PropertyType -Force -Confirm:$false -ErrorAction Stop | Out-Null\r\n            }\r\n            catch {\r\n                Write-Error \"[Error] Unable to Set registry key for $Name please see below error!\"\r\n                Write-Error $_\r\n                exit 1\r\n            }\r\n            Write-Host \"Set $Path$Name to $($(Get-ItemProperty -Path $Path -Name $Name -ErrorAction Ignore).$Name)\"\r\n        }\r\n    }\r\n\r\n    # This function is to make it easier to parse Ninja Custom Fields.\r\n    function Get-NinjaProperty {\r\n        [CmdletBinding()]\r\n        Param(\r\n            [Parameter(Mandatory = $True, ValueFromPipeline = $True)]\r\n            [String]$Name,\r\n            [Parameter()]\r\n            [String]$Type,\r\n            [Parameter()]\r\n            [String]$DocumentName\r\n        )\r\n\r\n        # If we're requested to get the field value from a Ninja document, we'll specify it here.\r\n        $DocumentationParams = @{}\r\n        if ($DocumentName) { $DocumentationParams[\"DocumentName\"] = $DocumentName }\r\n\r\n        # These two types require more information to parse.\r\n        $NeedsOptions = \"DropDown\", \"MultiSelect\"\r\n\r\n        # Grabbing document values requires a slightly different command.\r\n        if ($DocumentName) {\r\n            # Secure fields are only readable when they're a device custom field\r\n            if ($Type -Like \"Secure\") { throw \"$Type is an invalid type! Please check here for valid types. https:\/\/ninjarmm.zendesk.com\/hc\/en-us\/articles\/16973443979789-Command-Line-Interface-CLI-Supported-Fields-and-Functionality\" }\r\n\r\n            # We'll redirect the error output to the success stream to make it easier to error out if nothing was found or something else went wrong.\r\n            $NinjaPropertyValue = Ninja-Property-Docs-Get -AttributeName $Name @DocumentationParams 2&gt;&amp;1\r\n\r\n            # Certain fields require more information to parse.\r\n            if ($NeedsOptions -contains $Type) {\r\n                $NinjaPropertyOptions = Ninja-Property-Docs-Options -AttributeName $Name @DocumentationParams 2&gt;&amp;1\r\n            }\r\n        }\r\n        else {\r\n            # We'll redirect error output to the success stream to make it easier to error out if nothing was found or something else went wrong.\r\n            $NinjaPropertyValue = Ninja-Property-Get -Name $Name 2&gt;&amp;1\r\n\r\n            # Certain fields require more information to parse.\r\n            if ($NeedsOptions -contains $Type) {\r\n                $NinjaPropertyOptions = Ninja-Property-Options -Name $Name 2&gt;&amp;1\r\n            }\r\n        }\r\n\r\n        # If we received some sort of error it should have an exception property and we'll exit the function outputing nothing.\r\n        if ($NinjaPropertyValue.Exception) {\r\n            Write-Verbose $NinjaPropertyValue.ToString()\r\n            return $null \r\n        }\r\n        if ($NinjaPropertyOptions.Exception) {\r\n            Write-Verbose $NinjaPropertyOptions.ToString() \r\n            return $null \r\n        }\r\n\r\n        # This switch will compare the type given with the quoted string. If it matches, it'll parse it further; otherwise, the default option will be selected.\r\n        switch ($Type) {\r\n            \"Checkbox\" {\r\n                # Checkboxes come in as a string representing an integer. We'll need to cast that string into an integer and then convert it to a more traditional boolean.\r\n                [System.Convert]::ToBoolean([int]$NinjaPropertyValue)\r\n            }\r\n            \"Dropdown\" {\r\n                # Drop-down custom fields come in as a comma-separated list of GUIDs; we'll compare these with all the options and return just the option values selected instead of a GUID.\r\n                $Options = $NinjaPropertyOptions -replace '=', ',' | ConvertFrom-Csv -Header \"GUID\", \"Name\"\r\n                $Options | Where-Object { $_.GUID -eq $NinjaPropertyValue } | Select-Object -ExpandProperty Name\r\n            }\r\n            \"MultiSelect\" {\r\n                # Multi-Select custom fields come in as a comma-separated list of GUIDs; we'll compare these with all the options and return just the option values selected instead of a GUID.\r\n                $Options = $NinjaPropertyOptions -replace '=', ',' | ConvertFrom-Csv -Header \"GUID\", \"Name\"\r\n                $Selection = ($NinjaPropertyValue -split ',').trim()\r\n\r\n                foreach ($Item in $Selection) {\r\n                    $Options | Where-Object { $_.GUID -eq $Item } | Select-Object -ExpandProperty Name\r\n                }\r\n            }\r\n            default {\r\n                # If no type was given or not one that matches the above types just output what we retrieved.\r\n                $NinjaPropertyValue\r\n            }\r\n        }\r\n    }\r\n\r\n    # Pulling the document name from the script form.\r\n    if ($env:ninjaDocumentName -and $env:ninjaDocumentName -notlike \"null\") { $DocumentName = $env:ninjaDocumentName }\r\n\r\n    if ($DocumentName) {\r\n        Write-Host \"Retrieving values from Ninja Document '$DocumentName'...\"\r\n        $DocumentationParams = @{\r\n            DocumentName = $DocumentName\r\n        }\r\n    }\r\n\r\n    if (Test-IsElevated) {\r\n        Write-Host \"Checking custom fields for VPN configuration settings ...\"\r\n\r\n        # Grabbing Documentation or Custom Field Values if the parameter wasn't given or is the default value.\r\n        if (-not $AssumeUDPencapsulation) { $AssumeUDPencapsulation = Get-NinjaProperty -Name $UDPField -Type \"Checkbox\" @DocumentationParams }\r\n        if (-not $Name) { $Name = Get-NinjaProperty -Name $NameField @DocumentationParams }\r\n        if (-not $Server) { $Server = Get-NinjaProperty -Name $ServerField @DocumentationParams }\r\n        if (-not $PreSharedKey) { $PreSharedKey = Get-NinjaProperty -Name $PreSharedKeyField @DocumentationParams }\r\n        if (-not $TunnelType -and $TunnelType -eq \"Automatic\") { \r\n            $Tunnel = Get-NinjaProperty -Name $TunnelTypeField -Type \"Dropdown\" @DocumentationParams\r\n            if ($Tunnel) { $TunnelType = $Tunnel } \r\n        }\r\n        if (-not $AuthMethod) { $AuthMethod = Get-NinjaProperty -Name $AuthMethodField -Type \"Multiselect\" @DocumentationParams }\r\n        if (-not $EncryptionLevel) { $EncryptionLevel = Get-NinjaProperty -Name $EncryptionLevelField -Type \"Dropdown\" @DocumentationParams }\r\n        if (-not $DNSSuffix) { $DNSSuffix = Get-NinjaProperty -Name $DNSSuffixField @DocumentationParams }\r\n        if (-not $RememberCreds) { $RememberCreds = Get-NinjaProperty -Name $RememberCredsField -Type \"Checkbox\" @DocumentationParams }\r\n        if (-not $UseWinlogonCredential) { $UseWinLogonCredential = Get-NinjaProperty -Name $UseWinlogonCredsField -Type \"Checkbox\" @DocumentationParams }\r\n        if (-not $SplitTunneling) { $SplitTunneling = Get-NinjaProperty -Name $SplitTunnelingField -Type \"Checkbox\" @DocumentationParams }\r\n        if (-not $CreateShortcut) { $CreateShortcut = Get-NinjaProperty -Name $ShortcutField -Type \"Checkbox\" @DocumentationParams }\r\n        if (-not $IconDirectory) { $IconDirectory = Get-NinjaProperty -Name $IconDirectoryField @DocumentationParams }\r\n        if (-not $Url) { $Url = Get-NinjaProperty -Name $UrlField @DocumentationParams }\r\n    }\r\n    else {\r\n        Write-Warning \"Reading Custom Fields requires local admin privileges.\"\r\n    }\r\n\r\n    # If someone specifies something in the script form, we'll want to overwrite what the documentation says. Makes the script more useful for troubleshooting.\r\n    if ($env:vpnName -and $env:vpnName -notlike \"null\") { $Name = $env:vpnName }\r\n    if ($env:vpnServerAddress -and $env:vpnServerAddress -notlike \"null\") { $Server = $env:vpnServerAddress }\r\n    if ($env:presharedKey -and $env:presharedKey -notlike \"null\") { $PreSharedKey = $env:presharedKey }\r\n    if ($env:vpnTunnelType -and $env:vpnTunnelType -notlike \"null\") { $TunnelType = $env:vpnTunnelType }\r\n    if ($env:authenticationMethod -and $env:authenticationMethod -notlike \"null\") { $AuthMethod = $env:authenticationMethod }\r\n    if ($env:encryptionLevel -and $env:encryptionLevel -notlike \"null\") { $EncryptionLevel = $env:encryptionLevel }\r\n    if ($env:dnsSuffix -and $env:dnsSuffix -notlike \"null\") { $DNSSuffix = $env:dnsSuffix }\r\n    if ($env:iconPath -and $env:iconPath -notlike \"null\") { $Icon = $env:iconPath }\r\n    if ($env:iconUrl -and $env:iconUrl -notlike \"null\") { $Url = $env:iconUrl }\r\n    if ($env:iconDirectory -and $env:iconDirectory -notlike \"null\") { $IconDirectory = $env:iconDirectory }\r\n\r\n    # If an authentication method was given, we'll want to parse that and validate it.\r\n    if ($AuthMethod) {\r\n        $AuthSelections = ($AuthMethod.Split(',')).Trim()\r\n\r\n        $AuthSelections | ForEach-Object {\r\n            switch ($_) {\r\n                \"PAP\" { Write-Verbose \"PAP Selected\" }\r\n                \"Chap\" { Write-Verbose \"Chap Selected\" }\r\n                \"MSChapv2\" { Write-Verbose \"Eap Selected\" }\r\n                \"MachineCertificate\" { Write-Verbose \"MachineCertificate\" }\r\n                default {\r\n                    Write-Error \"$_ is invalid! The Valid auth types are 'PAP','Chap','MSChapv2' or 'MachineCertificate'.\"\r\n                    exit 1\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    # Validating encryption level. Not supporting \"No Encryption\". \r\n    if ($EncryptionLevel) {\r\n        switch ($EncryptionLevel) {\r\n            \"Optional\" { Write-Verbose \"Optional Selected\" }\r\n            \"Required\" { Write-Verbose \"Required Selected\" }\r\n            \"Maximum\" { Write-Verbose \"Maximum Selected\" }\r\n            default {\r\n                Write-Error \"$EncryptionLevel is invalid! The valid encryption levels are 'Optional', 'Required', or 'Maximum'.\"\r\n            }\r\n        }\r\n    }\r\n\r\n    # This will set the tunnel type.\r\n    switch ($TunnelType) {\r\n        \"L2TP\" { Write-Verbose \"L2TP Selected\" }\r\n        \"SSTP\" { Write-Verbose \"SSTP Selected\" }\r\n        \"IKEV2\" { Write-Verbose \"IKEV2 Selected\" }\r\n        \"Automatic\" { Write-Verbose \"Automatic Selected\" }\r\n        default { \r\n            Write-Error \"$TunnelType is invalid! The valid tunnel types are 'L2TP', 'SSTP', 'IKEv2', or 'Automatic'.\"\r\n            exit 1\r\n        }\r\n    }\r\n\r\n    # Error out if the only two mandatory parameters don't exist.\r\n    if (-not $Server -or -not $Name) {\r\n        Write-Error \"Name and Server are required! If using documentation fields or custom fields, double-check that your field exists and is readable by Automations.\"\r\n        exit 1\r\n    }\r\n\r\n    # Icons are minor, so if we're not given the information, we'll continue on without it and just let the technician know. They can always re-run it.\r\n    if (($Url -or $IconDirectory) -and -not $CreateShortcut) {\r\n        Write-Warning \"An icon was given, but Create Shortcut was never used? Ignoring icon info...\"\r\n        $Url = $null\r\n        $Icon = $null\r\n        $IconDirectory = $null\r\n    }\r\n\r\n    # Icons are minor, so if we're not given the information, we'll continue on without it and just let the technician know. They can always re-run it.\r\n    if ($Url -and -not $IconDirectory) {\r\n        Write-Warning \"An icon was given, but a place to store it wasn't? Use Icon Directory box to specify a directory to store it. (You may want this directory to be accessible by all users)\"\r\n        Write-Warning \"Ignoring supplied icon info.\"\r\n        $Icon = $null\r\n        $Url = $null\r\n    }\r\n}\r\nprocess {\r\n    # Checking for existing VPNs\r\n    $UserVPNs = Get-VpnConnection -Name $Name -EA Ignore\r\n    $GlobalVPNs = Get-VpnConnection -Name $Name -AllUserConnection -EA Ignore\r\n\r\n    # If the overwrite parameter wasn't specified, we'll error out as we won't be able to create the VPN.\r\n    if (($UserVPNs -or $GlobalVPNs) -and -not $Overwrite) {\r\n        Write-Error \"$Name already exists! Use -Overwrite to replace it.\"\r\n        if ($GlobalVPNs -and -not (Test-IsElevated)) { Write-Error \"$($GlobalVPNs.Name) requires elevation to replace\/overwrite.\" }\r\n        exit 1\r\n    }\r\n\r\n    # Removing previous VPNs if overwrite was specified.\r\n    if ($UserVPNs -and $Overwrite) {\r\n        $UserVPNs | Remove-VpnConnection -Force\r\n    }\r\n    \r\n    if ($GlobalVPNs -and $Overwrite) {\r\n        if (Test-IsElevated) {\r\n            $GlobalVPNs | Remove-VpnConnection -AllUserConnection -Force \r\n        }\r\n        else {\r\n            Write-Error \"$($GlobalVPNs.Name) requires elevation to replace\/overwrite.\"\r\n            exit 1\r\n        }\r\n    }\r\n\r\n    # Setting the AssumeUDPEncapsulationContextOnSendRule\r\n    if ($AssumeUDPencapsulation -and (Test-IsElevated)) {\r\n        Write-Warning \"AssumeUDPEncapsulation requires a reboot to take effect. This script does NOT reboot the machine.\"\r\n        Set-HKProperty -Name \"AssumeUDPEncapsulationContextOnSendRule\" -Path \"HKLM:SYSTEMCurrentControlSetServicesPolicyAgent\" -Value \"2\"\r\n    }\r\n\r\n    # Building the Add-VPNConnection command based on what information was entered\r\n    $ArgumentList = @{}\r\n    if ($SplitTunneling) { $ArgumentList[\"SplitTunneling\"] = $True }\r\n    if ($Server) { $ArgumentList[\"ServerAddress\"] = $Server }\r\n    if ($Name) { $ArgumentList[\"Name\"] = $Name }\r\n    if ($PreSharedKey) { $ArgumentList[\"L2TPPsk\"] = $PreSharedKey }\r\n    if ($TunnelType) { $ArgumentList[\"TunnelType\"] = $TunnelType }\r\n    if ($AuthMethod) { $ArgumentList[\"AuthenticationMethod\"] = $AuthSelections }\r\n    if ($EncryptionLevel) { $ArgumentList[\"EncryptionLevel\"] = $EncryptionLevel }\r\n    if ($DNSSuffix) { $ArgumentList[\"DnsSuffix\"] = $DNSSuffix }\r\n    if ($RememberCreds) { $ArgumentList[\"RememberCredential\"] = $True }\r\n    if ($UseWinlogonCredential) { $ArgumentList[\"UseWinLogonCredential\"] = $True }\r\n\r\n    # If the script wasn't run as system, only the current user should be able to access the VPN.\r\n    if (Test-IsSystem) { $ArgumentList[\"AllUserConnection\"] = $True }\r\n    $ArgumentList[\"Force\"] = $True\r\n    $ArgumentList[\"Passthru\"] = $True\r\n\r\n    Add-VpnConnection @ArgumentList | Format-Table -Property Name, ServerAddress, TunnelType, EncryptionLevel, AllUserConnection, SplitTunneling | Out-String | Write-Host\r\n\r\n    switch (Test-IsSystem) {\r\n        $True {\r\n            $ShortcutPath = \"$env:PublicDesktop$Name.lnk\"\r\n            $RasFile = Join-Path $env:PROGRAMDATA \"MicrosoftNetworkConnectionsPbkrasphone.pbk\"\r\n        }\r\n        default { \r\n            $ShortcutPath = \"$([Environment]::GetFolderPath(\"Desktop\"))$Name.lnk\"\r\n            $RasFile = Join-Path $env:APPDATA \"MicrosoftNetworkConnectionsPbkrasphone.pbk\"\r\n        }\r\n    }\r\n\r\n    if (-not (Test-Path $RasFile -EA Ignore)) { \r\n        Write-Error \"Failed to create vpn!\"\r\n        exit 1\r\n    }\r\n\r\n    # All Windows VPNs get a phonebook entry; we're going to check that the previous Add-VPNConnection was successful by looping through each line in the phonebook.\r\n    $Phonebook = Get-Content -Path $RasFile\r\n\r\n    for ($lineNumber = 0; $lineNumber -lt $Phonebook.Length; $lineNumber++) {\r\n        if ($Phonebook[$lineNumber] -eq \"[$Name]\") {\r\n            $Entry = $lineNumber\r\n            break\r\n        }\r\n    }\r\n\r\n    # If the VPN wasn't found, we're going to error out.\r\n    if ($Entry -notmatch \"d\") {\r\n        Write-Error \"Failed to create vpn!\"\r\n        exit 1\r\n    }\r\n\r\n    if ($CreateShortcut) {\r\n        if ($IconDirectory -and -not (Test-Path $IconDirectory -ErrorAction SilentlyContinue)) {\r\n            New-Item -ItemType Directory -Path $IconDirectory | Out-Null\r\n        }\r\n\r\n        # If we're given a URL, we'll want to download it.\r\n        if ($Url) {\r\n            $DownloadArguments = @{\r\n                URL  = $Url\r\n                Path = \"$IconDirectoryvpnscript-$Name.png\"\r\n            }\r\n            if ($SkipSleep) { $DownloadArguments[\"SkipSleep\"] = $True }\r\n\r\n            Invoke-Download @DownloadArguments\r\n\r\n            if (Test-Path \"$IconDirectoryvpnscript-$Name.png\" -ErrorAction SilentlyContinue) {\r\n                $Icon = \"$IconDirectoryvpnscript-$Name.png\"\r\n            }\r\n            else {\r\n                $Icon = $Null\r\n            }\r\n        }\r\n    \r\n        # This will convert the base64 into an image and save it to the temp folder.\r\n        if ($IconBase64 -and $IconDirectory -and -not $Icon -and -not $Url) {\r\n            Write-Verbose \"Converting Icon base64 to original image and saving to $IconDirectory...\"\r\n\r\n            ConvertFrom-Base64 -Base64 $IconBase64 -Path \"$IconDirectoryvpnscript-$Name.Png\"\r\n            \r\n            if (Test-Path \"$IconDirectoryvpnscript-$Name.Png\" -ErrorAction SilentlyContinue) {\r\n                $Icon = \"$IconDirectoryvpnscript-$Name.Png\"\r\n            }\r\n            else {\r\n                $Icon = $Null\r\n            }\r\n        }\r\n    \r\n        if ($Icon) {\r\n            Write-Verbose \"Converting image to icon and saving to $IconDirectoryvpnscript-$((Get-FileHash -Path $Icon -Algorithm MD5).Hash).ico ...\"\r\n\r\n            $NewName = \"vpnscript-$((Get-FileHash -Path $Icon -Algorithm MD5).Hash).ico\"\r\n            ConvertFrom-Image -ImagePath $Icon -Path \"$IconDirectory$NewName\"\r\n\r\n            if (Test-Path \"$IconDirectory$NewName\" -ErrorAction SilentlyContinue) {\r\n                $Icon = \"$IconDirectory$NewName\"\r\n            }\r\n            else {\r\n                $Icon = $Null\r\n            }\r\n        }\r\n    }\r\n\r\n    if ($CreateShortcut) {\r\n        $ShortcutArgs = @{\r\n            Path       = $ShortcutPath\r\n            Target     = \"rasphone.exe\"\r\n            Arguments  = \"-d `\"$Name`\"\"\r\n            WorkingDir = \"$env:SystemRootSystem32\"\r\n        }\r\n        if ($Icon) { $ShortcutArgs[\"IconPath\"] = $Icon } \r\n\r\n        New-Shortcut @ShortcutArgs\r\n    }\r\n\r\n    exit 0\r\n}\r\nend {\r\n    \r\n    \r\n    \r\n}<\/pre>\n<p>&nbsp;<\/p>\n\n<div class=\"in-context-cta\"><p>Accedi a oltre 700 script nel Dojo NinjaOne<\/p>\n<p><a href=\"https:\/\/www.ninjaone.com\/it\/prova-gratuita\/\">Ottieni l&#8217;accesso<\/a><\/p>\n<\/div>\n<h2>Analisi dettagliata<\/h2>\n<p>Lo script opera creando una connessione VPN utilizzando il client VPN integrato di Windows. Supporta diversi tipi di VPN (come L2TP, SSTP, IKEV2) e metodi di autenticazione. Lo script pu\u00f2 recuperare i dettagli della configurazione VPN da un documento NinjaOne o da campi personalizzati, offrendo flessibilit\u00e0 nella distribuzione.<\/p>\n<h2>Funzionalit\u00e0 chiave:<\/h2>\n<ul>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"1\" data-aria-level=\"1\"><strong>Configurazione VPN<\/strong>: Configura la VPN con opzioni per il tipo di tunnel, i metodi di autenticazione, i livelli di crittografia e altro ancora.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"2\" data-aria-level=\"1\"><strong>Campi personalizzati e documentazione<\/strong>: Consente di estrarre le informazioni VPN da NinjaOne Documentation o da campi personalizzati specifici del dispositivo.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"3\" data-aria-level=\"1\"><strong>Gestione delle icone<\/strong>: Lo script per configurare una VPN pu\u00f2 scaricare un&#8217;immagine per l&#8217;icona del collegamento VPN e anche convertirla nel formato richiesto.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"4\" data-aria-level=\"1\"><strong>Creazione di collegamenti<\/strong>: \u00c8 in grado di creare un collegamento sul desktop per facilitare l&#8217;accesso alla VPN.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"4\" data-aria-level=\"1\"><strong>Modifica del registro<\/strong>: Per alcune VPN, modifica il registro di Windows per abilitare l&#8217;incapsulamento UDP.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"4\" data-aria-level=\"1\"><strong>Opzione di sovrascrittura<\/strong>: Pu\u00f2 sovrascrivere una connessione VPN esistente con lo stesso nome.<\/li>\n<\/ul>\n<h2>Casi d&#8217;uso potenziali<\/h2>\n<p>L&#8217;amministratore IT di un&#8217;azienda di medie dimensioni deve implementare una connessione VPN sicura per tutti i dipendenti remoti. Utilizzando lo script per configurare una VPN, \u00e8 possibile stabilire rapidamente una configurazione VPN coerente su tutti i dispositivi, garantendo un accesso sicuro alla rete aziendale.<\/p>\n<h2>Confronti<\/h2>\n<p>Tradizionalmente, le VPN vengono configurate manualmente attraverso l&#8217;interfaccia di Windows o utilizzando script individuali. Il presente script per configurare una VPN\u00a0 offre un approccio pi\u00f9 unificato e automatizzato, riducendo i tempi e i potenziali errori rispetto all&#8217;impostazione manuale.<\/p>\n<h2>Domande frequenti<\/h2>\n<ul>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"3\" data-aria-level=\"1\"><strong>Lo script pu\u00f2 gestire diversi tipi di VPN?<\/strong><br \/>\nS\u00ec, supporta i tipi L2TP, SSTP, IKEV2 e Automatic.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"4\" data-aria-level=\"1\"><strong>\u00c8 possibile utilizzare questo script senza la documentazione NinjaOne?<\/strong><br \/>\nAssolutamente s\u00ec, pu\u00f2 funzionare con o senza la documentazione NinjaOne.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"5\" data-aria-level=\"1\"><strong>In che modo lo script per configurare una VPN migliora la sicurezza?<\/strong><br \/>\nLa standardizzazione delle configurazioni VPN riduce al minimo il rischio di configurazioni errate, migliorando la sicurezza complessiva.<\/li>\n<\/ul>\n<h2>Implicazioni<\/h2>\n<p>L&#8217;utilizzo di questo script, soprattutto nelle grandi distribuzioni, potrebbe migliorare significativamente la sicurezza della rete garantendo l&#8217;uniformit\u00e0 delle configurazioni VPN. Tuttavia, \u00e8 fondamentale mantenere aggiornato lo script per adattarlo a qualsiasi modifica degli standard VPN o agli aggiornamenti di Windows.<\/p>\n<h2>Raccomandazioni<\/h2>\n<ul>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"6\" data-aria-level=\"1\"><strong>Testa prima della distribuzione<\/strong>: Testa sempre lo script per configurare una VPN in un ambiente controllato prima di utilizzarlo su larga scala.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"7\" data-aria-level=\"1\"><strong>Mantieniti aggiornato<\/strong>: Aggiorna regolarmente lo script per allinearlo ai pi\u00f9 recenti standard VPN e agli aggiornamenti di Windows.<\/li>\n<li data-leveltext=\"\uf0b7\" data-font=\"Symbol\" data-listid=\"1\" data-list-defn-props=\"{&quot;335552541&quot;:1,&quot;335559684&quot;:-2,&quot;335559685&quot;:720,&quot;335559991&quot;:360,&quot;469769226&quot;:&quot;Symbol&quot;,&quot;469769242&quot;:[8226],&quot;469777803&quot;:&quot;left&quot;,&quot;469777804&quot;:&quot;\uf0b7&quot;,&quot;469777815&quot;:&quot;hybridMultilevel&quot;}\" data-aria-posinset=\"8\" data-aria-level=\"1\"><strong>Archiviazione sicura<\/strong>: Archivia il tuo script e le relative credenziali in modo sicuro per evitare accessi non autorizzati.<\/li>\n<\/ul>\n<h2>Considerazioni finali<\/h2>\n<p>Nel contesto della gestione delle VPN, NinjaOne offre una solida piattaforma per i professionisti IT, <a href=\"https:\/\/www.ninjaone.com\/it\/efficienza-it\/\">migliorando l&#8217;efficienza<\/a> e la sicurezza delle attivit\u00e0 di gestione della rete. Questo script per configurare una VPN, in combinazione con le funzionalit\u00e0 di NinjaOne, pu\u00f2 semplificare la distribuzione delle VPN, rendendolo uno strumento prezioso nell&#8217;arsenale della moderna gestione IT.<\/p>\n","protected":false},"author":35,"featured_media":207408,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_acf_changed":false,"_relevanssi_hide_post":"","_relevanssi_hide_content":"","_relevanssi_pin_for_all":"","_relevanssi_pin_keywords":"","_relevanssi_unpin_keywords":"","_relevanssi_related_keywords":"","_relevanssi_related_include_ids":"","_relevanssi_related_exclude_ids":"","_relevanssi_related_no_append":"","_relevanssi_related_not_related":"","_relevanssi_related_posts":"","_relevanssi_noindex_reason":"","_lmt_disableupdate":"no","_lmt_disable":""},"operating_system":[4212],"use_cases":[4269],"class_list":["post-208179","script_hub","type-script_hub","status-publish","has-post-thumbnail","hentry","script_hub_category-windows"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/script_hub\/208179","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/script_hub"}],"about":[{"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/types\/script_hub"}],"author":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/users\/35"}],"replies":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/comments?post=208179"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/media\/207408"}],"wp:attachment":[{"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/media?parent=208179"}],"wp:term":[{"taxonomy":"script_hub_category","embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/operating_system?post=208179"},{"taxonomy":"use_cases","embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/use_cases?post=208179"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}