Untitled

 avatar
qubit3265
plain_text
a year ago
15 kB
4
Indexable
Never
# Inputs
$blockDesktopInstall = "false"
<#	
	.NOTES
	===========================================================================
	 Created with: 	SAPIEN Technologies, Inc., PowerShell Studio 2021 v5.8.187
	 Created on:   	18/07/2021 23:57
	 Created by:   	Dvir
	 Organization: 	YP
	 Filename:     	OpenVPN 3 - GUI (Install)
	===========================================================================
	.DESCRIPTION
		A full script to install and config a full profile for the user.
#>

$profileContent = @"
dev tun
persist-tun
persist-key
data-ciphers-fallback AES-128-CBC
auth SHA256
tls-client
client
resolv-retry infinite
remote XXX.XXX.XXX.XXX 1194 udp4
setenv opt block-outside-dns
auth-user-pass
#ca [inline]
#tls-auth [inline]
client-cert-not-required
key-direction 1
remote-cert-tls server

<ca>
-----BEGIN CERTIFICATE-----
XXX
-----END CERTIFICATE-----
</ca>

<tls-auth>
-----BEGIN OpenVPN Static key V1-----
XXX
-----END OpenVPN Static key V1-----
</tls-auth>
"@ <# Profile #>
$profileName = "profile.ovpn"
$profileDir = "$env:SystemDrive\Temp"

$InstallParameters = @{
	installSource = "https://openvpn.net/downloads/openvpn-connect-v3-windows.msi"
	configFile    = ""
	configContent = ""
	installZip    = ""
	installName   = "openvpn-connect.msi"
	zipDir	      = ""
	unzipDir	  = ""
	installDir    = "$env:windir\Temp\OpenVPNconnect"
	installTests  = "$env:ProgramFiles\OpenVPN Connect\OpenVPNConnect.exe", "${env:ProgramFiles(x86)}\OpenVPN Connect\OpenVPNConnect.exe"
	installArgument = "Start-Process -FilePath `"$env:windir\Temp\OpenVPNconnect\openvpn-connect.msi`" -ArgumentList `"/qb`" -Wait -Verbose -ErrorAction Ignore"
	cleanFilesOnExit = $false
	sleepTimer    = "5"
	retryCountMax = "5"
	brokenTestMax = "5" <# Max tests before the script closing from a broken loop #>
}

function Install-Program
{
	<#
	.SYNOPSIS
		Version 1.1

	.DESCRIPTION
		Smart install programs script, multi options.

	.EXAMPLE
	$InstallParameters = @{
		installSource = "URL"
		configFile    = "O365Office.xml"
		configContent = $configContent
		installZip    = ""
		installName   = "setup.exe"
		zipDir	      = ""
		unzipDir	  = ""
		installDir    = "$env:windir\Temp"
		installTests  = "$env:ProgramFiles\Microsoft Office\root\Office16\OUTLOOK.EXE", "${env:ProgramFiles(x86)}\Microsoft Office\root\Office16\OUTLOOK.EXE", "$env:ProgramFiles\Microsoft Office\Office16\OUTLOOK.EXE", "${env:ProgramFiles(x86)}\Microsoft Office\Office16\OUTLOOK.EXE", "$env:ProgramFiles\Microsoft Office\Office15\OUTLOOK.EXE", "${env:ProgramFiles(x86)}\Microsoft Office\Office15\OUTLOOK.EXE"
		installArgument = "Start-Process -FilePath `"$env:windir\Temp\setup.exe`" -ArgumentList `'/configure `"$env:windir\Temp\O365Office.xml`"`' -Wait -Verbose -ErrorAction Ignore"
		cleanFilesOnExit = $true
		sleepTimer    = "5"
		retryCountMax = "5"
		brokenTestMax = "5"
	}
	
	Install-Program @InstallParameters
#>
	[CmdletBinding()]
	param (
		[Parameter(Mandatory = $true)]
		[uri]$installSource,
		[Parameter(Mandatory = $false)]
		[String]$configFile,
		[Parameter(Mandatory = $false)]
		[String]$configContent,
		[Parameter(Mandatory = $false)]
		[String]$installZip,
		[Parameter(Mandatory = $false)]
		[String]$installName,
		[Parameter(Mandatory = $false)]
		[String]$zipDir,
		[Parameter(Mandatory = $false)]
		[String]$unzipDir,
		[Parameter(Mandatory = $false)]
		[String]$installDir,
		[Parameter(Mandatory = $false)]
		[Array]$installTests,
		[Parameter(Mandatory = $false)]
		[String]$installArgument,
		[Parameter(Mandatory = $true)]
		[Switch]$cleanFilesOnExit,
		[Parameter(Mandatory = $true)]
		[int]$sleepTimer,
		[Parameter(Mandatory = $false)]
		[int]$retryCountMax,
		[Parameter(Mandatory = $true)]
		[int]$brokenTestMax
	)
	
	[Switch]$loop = $true <# Base loop, do not change #>
	[int]$retryCount = "0" <# Loop starting at 0, do not change #>
	[int]$brokenTest = "0" <# Test starting at 0, do not change #>
	[Switch]$startInstall = $true <# Base status, do not change #>
	[Switch]$skipFailTest = $false
	if (([int]$retryCountMax -eq "0") -or (([string]::IsNullOrEmpty($retryCountMax)))) { [Switch]$skipFailTest = $true }
	
	if (!([string]::IsNullOrEmpty($installTests)))
	{ foreach ($installTest in $installTests) { if (Test-Path -Path $installTest) { [Switch]$startInstall = $false; break } } <# Test for install #> }
	else
	{
		[Switch]$startInstall = $true
		$installTest = $false
		$skipFailTest = $true
	}
	
	function Create-Folders
	{
		[CmdletBinding()]
		param (
			[Parameter(Position = 0, Mandatory = $true)]
			[System.Array]$folders
		)
		
		foreach ($folder in $folders)
		{ if (!([System.IO.Directory]::Exists($folder))) { New-Item $folder -ItemType Directory | Out-Null } } <# Create directory if not exists #>
	}
	
	if (!([string]::IsNullOrEmpty($unzipDir))) { [System.Array]$foldersArray += $unzipDir }
	if (!([string]::IsNullOrEmpty($zipDir))) { [System.Array]$foldersArray += $zipDir }
	if (!([string]::IsNullOrEmpty($installDir))) { [System.Array]$foldersArray += $installDir }
	Create-Folders -Folders $foldersArray
	
	if ([Switch]$startInstall)
	{
		do <# Install and verify #>
		{
			function Clean-InstallFiles
			{
				if (!([string]::IsNullOrEmpty($zipDir)))
				{
					if (Test-Path -Path "$zipDir\$installZip") { Remove-Item -Path "$zipDir\$installZip" -Force -Verbose -ErrorAction SilentlyContinue }
					if (Test-Path -Path "$installDir") { Remove-Item -Path "$installDir" -Recurse -Force -Verbose -ErrorAction SilentlyContinue }
				}
				else
				{
					if (Test-Path -Path "$installDir\$installName") { Remove-Item -Path "$installDir\$installName" -Force -Verbose -ErrorAction SilentlyContinue }
				}
				if (!([string]::IsNullOrEmpty($configFile)))
				{
					If (Test-Path "$installDir\$configFile") { Remove-Item -Path "$installDir\$configFile" -Force -Verbose -ErrorAction SilentlyContinue }
				}
			}
			
			if (!(Test-Path -Path $installTest)) <# Download & Unzip block #>
			{
				if ([int]$retryCount -eq "0")
				{
					$retryCount += 1
					if (!([string]::IsNullOrEmpty($installZip))) <# Download block #>
					{
						if (!(Test-Path -Path "$zipDir\$installZip")) <# Lookup if the zip is there, Download #>
						{
							Write-Verbose "Downloading to `"$zipDir\$installZip`""
							try { Invoke-WebRequest $installSource -OutFile "$zipDir\$installZip" -Verbose -ErrorAction Ignore | Wait-Job }
							catch [System.Net.WebException]
							{
								Write-Output "Link Broken / No network."
								exit
							}
						}
						
						If (Test-Path -Path "$zipDir\$installZip") <# Unzip block #>
						{
							$ErrorOccured = $false
							try { Expand-Archive -Path "$zipDir\$installZip" -DestinationPath "$unzipDir" -Force -Verbose -ErrorAction Ignore }
							catch
							{
								Write-Output "The zip `"$zipDir\$installZip`" is broken, downloading again..."
								Clean-InstallFiles
								$retryCount -= 1
								$ErrorOccured = $true
							}
						}
					}
					else
					{
						if (!(Test-Path -Path "$installName")) <# Lookup if the file is there, Download #>
						{
							Write-Verbose "Downloading to `"$installDir\$installName`""
							try { Invoke-WebRequest $installSource -OutFile "$installDir\$installName" -Verbose -ErrorAction Ignore | Wait-Job }
							catch [System.Net.WebException] <# This catch is here in case of a dead link, if you get this error the link is either dead or broken. #>
							{
								Write-Output "Link Broken / No network."
								exit
							}
						}
					}
					if (!($ErrorOccured)) <# Run install block #>
					{
						
						if (!([string]::IsNullOrEmpty($configFile)) -and (!([string]::IsNullOrEmpty($configFile))))
						{ New-Item -Path $installDir -Name $configFile -ItemType "file" -Value $configContent -Force -Verbose }
						
						if (!([string]::IsNullOrEmpty($installArgument))) <# If installArgument is empty there is nothing to install, skip. #>
						{
							Write-Output "Running install.."
							Write-Output "Command: `"$installArgument`""
							try { Invoke-Expression -Command $installArgument }
							catch
							{
								Write-Output "The file `"$installDir\$installName`" is broken, downloading again..."
								Clean-InstallFiles
								$retryCount -= 1
							}
						}
					}
				}
			}
			
			if (!($skipFailTest))
			{
				foreach ($installTest in $installTests) { if (Test-Path -Path $installTest) { break } } <# Test for install #>
				
				if (Test-Path -Path $installTest)
				{
					Write-Output "Installed!"
					if ([Switch]$cleanFilesOnExit) { Clean-InstallFiles }
					[Switch]$loop = $false
				}
				
				if (!(Test-Path -Path $installTest))
				{
					if ($retryCount -gt $retryCountMax)
					{
						Write-Output "Failed to install..."
						Clean-InstallFiles
						[Switch]$loop = $false
					}
					elseif ([int]$retryCount -eq "0")
					{
						#Write-Output "Test"
					} <# Do nothing #>
					else
					{
						Write-Output "Testing install, attempt number $retryCount, Waiting $sleepTimer secs..."
						Start-Sleep -Seconds $sleepTimer
						$retryCount += 1
					} <# Sleep before next loop #>
				}
			}
			else { [Switch]$loop = $false }
			
			$brokenTest += 1 <# If this loop hits $brokenTestMax the script will stop. #>
			if ($brokenTest -gt $brokenTestMax)
			{
				Write-Output "The script is broken, closing."
				exit
			}
		}
		While ($loop)
	}
	else
	{
		Write-Output "The program is already installed on this machine"
	}
}

function OpenVPN-Profile
{	
	Write-Host "Updating the config file..."
	if (!(Test-Path -Path $profileDir)) { New-Item -Path "$profileDir" -ItemType "directory" -Force } <# Lookup if the temp folder is there and create #>
	If (Test-Path "$profileDir\$profileName") { Remove-Item -Path "$profileDir\$profileName" -Force }
	If (!(test-path "$profileDir\$profileName")) { New-Item -Path $profileDir -Name $profileName -ItemType "file" -Value $profileContent -Force | Out-Null }
}

function OpenVPN-Remove-Service
{
	Write-Output "Removing OpenVPN as a service, to replace with a GUI"
	Get-Process | Where-Object { $_.Name -eq "OpenVPNConnect" } | Stop-Process -Force
	Start-Process "C:\Program Files\OpenVPN Connect\ovpnconnector.exe" -Args "stop" -Wait
	Start-Process "C:\Program Files\OpenVPN Connect\ovpnconnector.exe" -Args "unset-config profile" -Wait
	Start-Process "C:\Program Files\OpenVPN Connect\ovpnconnector.exe" -Args "remove" -Wait
}

function OpenVPN-Config-GUI
{
	Write-Host "Setting up the OpenVPN GUI..."
	[ScriptBlock]$scriptBlock = {
		$localAdmin = "Administrator"
		$profileName = "profile.ovpn"
		
		$exeLocation = "$env:Programfiles\OpenVPN Connect\OpenVPNConnect.exe"
		$profileDir = "$env:SystemDrive\Temp"
		$profileLocation = "$profileDir\$profileName"
		
		$username = $env:USERNAME
		if ($username -contains "Administrator")
		{
			if ($username -match "Administrator") { }
			else { $username = $username -replace "Administrator", "" }
		}
		$profileShortName = $profileName -Replace ".ovpn", ""
		$argumentList = "--minimize --accept-gdpr --skip-startup-dialogs --import-profile=$profileLocation --name=$profileShortName --username=$username --set-settings=launch-options --value=connect-latest --set-settings=seamless-tunnel --value=false --set-settings=enable-crash-reporting --value=true"
		
		Write-Host "Username: $username"
		Write-Host "Profile: $profileLocation"
		Write-Host "EXE: $exeLocation"
		
		Start-Process -FilePath $exeLocation -ArgumentList $argumentList <# Run the config #>
		Start-Sleep -Seconds 5
		Start-Process -FilePath $exeLocation <# Start the program #>
	}
	try { Invoke-AsCurrentUser -ScriptBlock $scriptBlock -CacheToDisk -ErrorAction Stop }
	catch [Microsoft.PowerShell.Commands.WriteErrorException] { Invoke-Command -Command $scriptBlock }
}

function Install-CustomModule
{
	param (
		[Parameter(Mandatory = $true)]
		[Array]$Modules
	)
	foreach ($module in $modules)
	{
		try
		{
			#Write-Output "Importing module '$module'"
			function Update-CustomModule
			{
				[cmdletbinding()]
				[outputtype("moduleInfo")]
				Param (
					[Parameter(Position = 0, HelpMessage = "Enter a module name or names. Wildcards are allowed.")]
					[ValidateNotNullorEmpty()]
					[string[]]$Name = "*"
				)
				
				Write-Verbose "Getting installed modules"
				Try
				{
					$modules = Get-Module -Name $name -ListAvailable -ErrorAction Stop
				}
				Catch
				{
					Throw $_
				}
				
				if ($modules)
				{
					Write-Verbose "Found $($modules.count) matching modules"
					#group to identify modules with multiple versions installed
					Write-Verbose "Grouping modules"
					$g = $modules | Group-Object name -NoElement | Where-Object count -GT 1
					
					Write-Verbose "Filter to modules from the PSGallery"
					$gallery = $modules.where({ $_.repositorysourcelocation })
					
					Write-Verbose "Comparing to online versions"
					foreach ($module in $gallery)
					{
						
						#find the current version in the gallery
						Try
						{
							Write-Verbose "Looking online for $($module.name)"
							$online = Find-Module -Name $module.name -Repository PSGallery -ErrorAction Stop
							#compare versions
							if (($online.version -as [version]) -gt ($module.version -as [version]))
							{
								Uninstall-Module -Name $module -AllVersions -Force
								Install-Module -Name $module -Scope AllUsers -AllowClobber -Force
							}
						}
						Catch
						{
							#Write-Warning "Module $($module.name) was not found in the PSGallery"
						}
						
					} #foreach
				}
				else
				{
					Write-Warning "No matching modules found."
				}
				
				Write-Verbose "Check complete"
			}
			
			Update-CustomModule -Name "ExchangeOnlineManagement" -Verbose:$false
			Import-Module $module -ErrorAction Stop
		}
		catch
		{
			Write-Output "Could not find '$module' module, installing..."
			Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force -Verbose:$false *>$null
			Install-Module -Name $module -Scope AllUsers -AllowClobber -Force
			Import-Module $module -ErrorAction Stop
			#Write-Output "Importing module '$module'"
		}
	}
}

if (Get-WmiObject -Class win32_systemenclosure | Where-Object { $_.chassistypes -eq 9 -or $_.chassistypes -eq 10 -or $_.chassistypes -eq 14 }) { $Chasis = "Laptop" }
if (Get-WmiObject -Class win32_battery) { $Chasis = "Laptop" } <# Shows battery status , if true then the machine is a laptop. #>
else { $Chasis = "Desktop" }

if ($blockDesktopInstall -eq "true")
{
	Write-Output "Chasis: $Chasis, Block Desktop install is set to `"$blockDesktopInstall`""
	if (($Chasis -eq "Laptop"))
	{
		Install-CustomModule -modules "RunAsUser"
		Install-Program @InstallParameters
		OpenVPN-Profile
		OpenVPN-Remove-Service
		OpenVPN-Config-GUI
	}
	else { OpenVPN-Remove-Service; Write-Output "PC is a $Chasis, skipping install." }
}