{"id":815652,"date":"2026-05-28T12:25:52","date_gmt":"2026-05-28T12:25:52","guid":{"rendered":"https:\/\/www.ninjaone.com\/?post_type=script_hub&#038;p=815652"},"modified":"2026-05-28T12:25:52","modified_gmt":"2026-05-28T12:25:52","slug":"configuracao-de-um-windows-vpn-com-powershell","status":"publish","type":"script_hub","link":"https:\/\/www.ninjaone.com\/pt-br\/script-hub\/configuracao-de-um-windows-vpn-com-powershell\/","title":{"rendered":"Simplifique a configura\u00e7\u00e3o de sua VPN: Configurar uma VPN com o PowerShell"},"content":{"rendered":"<h2>Principais conclus\u00f5es<\/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>Configura\u00e7\u00e3o automatizada de VPN<\/strong>: O script automatiza a cria\u00e7\u00e3o de conex\u00f5es VPN no Windows, aumentando <a href=\"https:\/\/www.ninjaone.com\/pt-br\/eficiencia\/\">a efici\u00eancia<\/a>.<\/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>Suporta v\u00e1rios tipos de VPN<\/strong>: Compat\u00edvel com <a href=\"https:\/\/www.ninjaone.com\/it-hub\/gerenciamento-de-servicos-de-ti\/what-is-the-layer-2-tunneling-protocol\/\">L2TP<\/a>, <a href=\"https:\/\/www.ninjaone.com\/it-hub\/seguranca-de-endpoints\/what-is-secure-socket-tunneling-protocol\/\">SSTP<\/a>, <a href=\"https:\/\/www.ninjaone.com\/it-hub\/remote-access\/what-is-ikev2\/\">IKEV2<\/a> e sele\u00e7\u00e3o autom\u00e1tica de tipos de 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>Flexibilidade na configura\u00e7\u00e3o<\/strong>: Pode extrair configura\u00e7\u00f5es de VPN da Documenta\u00e7\u00e3o Ninja ou de campos personalizados para configura\u00e7\u00f5es personalizadas.<\/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>Seguran\u00e7a aprimorada<\/strong>: Padroniza as configura\u00e7\u00f5es de VPN em todos os dispositivos, reduzindo o risco de configura\u00e7\u00f5es incorretas.<\/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>Gerenciamento de atalhos e \u00edcones<\/strong>: Cria automaticamente atalhos na \u00e1rea de trabalho e gerencia os \u00edcones de atalho da 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>Modifica\u00e7\u00f5es no Registro do Windows<\/strong>: Ajusta configura\u00e7\u00f5es como o encapsulamento UDP no registro do Windows para necessidades espec\u00edficas de 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>Capacidade de substitui\u00e7\u00e3o<\/strong>: Oferece a op\u00e7\u00e3o de substituir as conex\u00f5es VPN existentes com o mesmo 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>Teste antes do uso generalizado<\/strong>: Aconselha-se testar o script em um ambiente controlado antes da aplica\u00e7\u00e3o ampla.<\/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>Atualiza\u00e7\u00f5es regulares necess\u00e1rias<\/strong>: Necess\u00e1rio atualizar o script para que seja compat\u00edvel com os mais recentes padr\u00f5es de VPN e atualiza\u00e7\u00f5es do 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>Gerenciamento seguro de scripts<\/strong>: \u00c9 importante armazenar o script e suas credenciais de forma segura para evitar acesso n\u00e3o autorizado.<\/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>Integra\u00e7\u00e3o com o NinjaOne<\/strong>: O script complementa a plataforma da NinjaOne, simplificando o gerenciamento de VPN em infraestruturas de TI.<\/li>\n<\/ul>\n<p>A integra\u00e7\u00e3o de <a href=\"https:\/\/www.ninjaone.com\/it-hub\/seguranca-de-endpoints\/what-is-a-virtual-private-network-vpn\/\">redes privadas virtuais (VPNs)<\/a> em ambientes corporativos e de TI \u00e9 essencial para manter o acesso seguro e remoto aos recursos organizacionais. \u00c0 medida que as empresas adotam cada vez mais pol\u00edticas de trabalho remoto e servi\u00e7os baseados em nuvem, a capacidade de configurar conex\u00f5es VPN de forma r\u00e1pida e segura se torna crucial. Nesse sentido, os scripts de automa\u00e7\u00e3o para a configura\u00e7\u00e3o da VPN desempenham um papel fundamental.<\/p>\n<h2>Hist\u00f3rico<\/h2>\n<p>O script do PowerShell fornecido foi projetado para automatizar o processo de configura\u00e7\u00e3o de uma conex\u00e3o VPN em ambientes Windows. Ele atende a profissionais de TI e <a href=\"https:\/\/www.ninjaone.com\/what-is-an-msp\/\">provedores de servi\u00e7os gerenciados (MSPs)<\/a> que configuram regularmente VPNs em v\u00e1rios dispositivos. Esse script n\u00e3o apenas economiza tempo, mas tamb\u00e9m garante a consist\u00eancia e reduz a probabilidade de erros manuais nas configura\u00e7\u00f5es de VPN.<\/p>\n<h2>O roteiro:<\/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>Acesse mais de 300 scripts no NinjaOne Dojo<\/p>\n<p><a href=\"https:\/\/www.ninjaone.com\/freetrialform\/\">Obter acesso<\/a><\/p>\n<\/div>\n<h2>Detalhamento<\/h2>\n<p>Esse script funciona criando uma conex\u00e3o VPN usando o cliente VPN integrado do Windows. Ele oferece suporte a v\u00e1rios tipos de VPN (como L2TP, SSTP, IKEV2) e m\u00e9todos de autentica\u00e7\u00e3o. O script pode recuperar detalhes de configura\u00e7\u00e3o da VPN de um documento Ninja ou de campos personalizados, oferecendo flexibilidade na implementa\u00e7\u00e3o.<\/p>\n<h2>Principais fun\u00e7\u00f5es:<\/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>Configura\u00e7\u00e3o de VPN<\/strong>: Ele configura a VPN com op\u00e7\u00f5es de tipo de t\u00fanel, m\u00e9todos de autentica\u00e7\u00e3o, n\u00edveis de criptografia e muito mais.<\/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>Campos personalizados e documenta\u00e7\u00e3o<\/strong>: Permite extrair informa\u00e7\u00f5es de VPN da documenta\u00e7\u00e3o Ninja ou de campos personalizados espec\u00edficos do 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>Gerenciamento de \u00edcones<\/strong>: O script pode fazer o download de uma imagem para o \u00edcone de atalho da VPN e at\u00e9 mesmo convert\u00ea-la para o formato necess\u00e1rio.<\/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>Cria\u00e7\u00e3o de atalhos<\/strong>: Ele tem a capacidade de criar um atalho na \u00e1rea de trabalho para facilitar o acesso \u00e0 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\u00e7\u00e3o de registro<\/strong>: Para determinadas VPNs, ele modifica o registro do Windows para ativar o encapsulamento 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>Op\u00e7\u00e3o de substitui\u00e7\u00e3o<\/strong>: Ele pode substituir uma conex\u00e3o VPN existente com o mesmo nome.<\/li>\n<\/ul>\n<h2>Casos de uso em potencial<\/h2>\n<p>Um administrador de TI de uma empresa de m\u00e9dio porte precisa implementar uma conex\u00e3o VPN segura para todos os funcion\u00e1rios remotos. Usando esse script, eles podem estabelecer rapidamente uma configura\u00e7\u00e3o de VPN consistente em todos os dispositivos, garantindo o acesso seguro \u00e0 rede da empresa.<\/p>\n<h2>Compara\u00e7\u00f5es<\/h2>\n<p>Tradicionalmente, as VPNs s\u00e3o configuradas manualmente por meio da interface do Windows ou usando scripts individuais. Esse script oferece uma abordagem mais unificada e automatizada, reduzindo o tempo e os poss\u00edveis erros em compara\u00e7\u00e3o com a configura\u00e7\u00e3o manual.<\/p>\n<h2>Implica\u00e7\u00f5es<\/h2>\n<p>O uso desse script, especialmente em grandes implanta\u00e7\u00f5es, pode aumentar significativamente a seguran\u00e7a da rede, garantindo uniformidade nas configura\u00e7\u00f5es de VPN. No entanto, \u00e9 fundamental manter o script atualizado para se adaptar a quaisquer altera\u00e7\u00f5es nos padr\u00f5es de VPN ou atualiza\u00e7\u00f5es do Windows.<\/p>\n<h2>Recomenda\u00e7\u00f5es<\/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>Teste antes da implementa\u00e7\u00e3o<\/strong>: Sempre teste o script em um ambiente controlado antes de us\u00e1-lo em larga escala.<\/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>Mantenha-se atualizado<\/strong>: Atualize regularmente o script para alinh\u00e1-lo com os padr\u00f5es de VPN e as atualiza\u00e7\u00f5es do Windows mais recentes.<\/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>Armazenamento seguro<\/strong>: Armazene seu script e as credenciais relacionadas de forma segura para evitar acesso n\u00e3o autorizado.<\/li>\n<\/ul>\n<h2>Considera\u00e7\u00f5es finais<\/h2>\n<p>No contexto do gerenciamento de VPN, o NinjaOne oferece uma plataforma robusta para profissionais de TI, <a href=\"https:\/\/www.ninjaone.com\/pt-br\/eficiencia\/\">aumentando a efici\u00eancia<\/a> e a seguran\u00e7a das tarefas de gerenciamento de rede. Esse script, em combina\u00e7\u00e3o com os recursos do NinjaOne, pode simplificar a implementa\u00e7\u00e3o da VPN, tornando-a uma ferramenta valiosa no arsenal do gerenciamento moderno de TI.<\/p>\n","protected":false},"author":35,"featured_media":193928,"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":[12460],"class_list":["post-815652","script_hub","type-script_hub","status-publish","has-post-thumbnail","hentry","script_hub_category-windows"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/script_hub\/815652","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/script_hub"}],"about":[{"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/types\/script_hub"}],"author":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/users\/35"}],"replies":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/comments?post=815652"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/media\/193928"}],"wp:attachment":[{"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/media?parent=815652"}],"wp:term":[{"taxonomy":"script_hub_category","embeddable":true,"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/operating_system?post=815652"},{"taxonomy":"use_cases","embeddable":true,"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/use_cases?post=815652"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}