Global.ps1
$Global:UpdateInfoURL = "https://updateservice.logeto.com/" $Global:DefaultVersion = "1.0.0" $Global:LogetoFolder = $env:ProgramData + "\Logeto\" $Global:DownloadFolder = "Downloads" $Global:UpdateFolder = "Update" $Global:SystemUpdateFolder = "SystemUpdate" $Global:RegistryFolder = "HKCU:\Software\Systemart s.r.o." $Global:RegistryFolderFallback = "HKLM:\Software\Systemart s.r.o." $Global:RegistryActiveHours = "HKLM:\SOFTWARE\Microsoft\WindowsUpdate\UX\Settings" $Global:RegistryScopeName = 'UpdateScope' $Global:RegistryActiveHoursStartName = 'ActiveHoursStart' $Global:RegistryActiveHoursEndName = 'ActiveHoursEnd' <# Return Json file with the product information. If version parameter is set it returns Json file only if higher version was found, otherwise returns null. #> function Get-LogetoUpdateInfo { Param( [parameter(Mandatory=$true)] [String] $Product, [parameter(Mandatory=$false)] [String] $Scope, [parameter(Mandatory=$false)] [String] $Version ) Write-LogetoProgress "Searching for new version. $Product $Scope $Version" "Get-LogetoUpdateInfo" $fileName = $Product if (![String]::IsNullOrEmpty($Scope)) { $fileName += "-" $fileName += $Scope } $fileName += ".json" $file = [System.IO.Path]::GetTempFileName(); try { try { Write-LogetoDebug "URL of the UpdateInfo file is $UpdateInfoURL$fileName" (New-Object System.Net.WebClient).DownloadFile($UpdateInfoURL + $fileName, $file) $json = (Get-Content -Raw -Path $file) | ConvertFrom-Json $downloadedVersion = $json | Select -ExpandProperty Version if (![String]::IsNullOrEmpty($Version)) { if ([System.Version]$downloadedVersion -gt [System.Version]$Version) { Write-LogetoDebug "UpdateInfo has been found!" return $json } else { Write-LogetoDebug "No newer UpdateInfo has been found!" return $null } } if (!$json) { Write-LogetoDebug "Last UpdateInfo has been found!" return $json } } finally { if (Test-Path $file) { Remove-Item $file -Force } } } catch [Exception] { #Write-Error $_.Exception.Message #return $null; throw } Write-LogetoDebug "No UpdateInfo has been found!" return $null; } <# Download and extract any Logeto product zip file into Download/ProductName folder #> function Get-LogetoProduct { Param( [parameter(Mandatory=$true)] $UpdateInfo, [parameter(Mandatory=$true)] [ValidateSet('Terminal', 'TerminalService')] $ProductName ) $folder = $LogetoFolder + $ProductName + "\" + $DownloadFolder try { [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true} Write-LogetoProgress "Downloading files" "ModuleGetLogetoProduct" $packageUrl = $UpdateInfo | Select -ExpandProperty PackageUrl if ($packageUrl.StartsWith("file://")) { #Update info is stored localy $packageUrl = $packageUrl.Replace("file://","") $packageUrl = "$LogetoFolder$packageUrl" Write-Host $packageUrl Invoke-LogetoExtract $packageUrl $folder } else { $zipFile = [System.IO.Path]::GetTempFileName(); try { #Package should be downloaded remotely (New-Object System.Net.WebClient).DownloadFile($packageUrl, $zipFile) Write-LogetoDebug "Downloaded ZipFile $zipFile (Get-LogetoProduct) extract to $folder" Invoke-LogetoExtract $zipFile $folder } finally { if (Test-Path $zipFile) { Remove-Item $zipFile -Force } } } Write-LogetoDebug "Downloading finished." } catch { throw Get-LogetoCustomException "Downloading the newest version failed with reason: $_.Exception.Message" "ScriptSystemartInstallerDownloadFailed" $resultExceptionThrown 1 } } <# Return the version of an appx package #> Function Get-LogetoAppxVersion([String] $packageName) { $packages = Get-AppxPackage | where Name -EQ $packageName if ($packages -ne $null) { return $packages.Version } return $DefaultVersion; } <# Return the version of exe file #> Function Get-LogetoExeVersion([String] $pathToExe) { if ([String]::IsNullOrEmpty($pathToExe) -or !(Test-Path $pathToExe)) { return $DefaultVersion } return (Get-Command $pathToExe).FileVersionInfo.FileVersion } <# Return path to the file of service #> Function Get-LogetoServicePath([String] $serviceName) { $service = (Get-WmiObject win32_service | ?{$_.Name -eq $serviceName}) if ($service) { return $service.PathName.Replace("`"","") } return $null } <# Create and return custom Logeto exception #> Function Get-LogetoCustomException($exceptionText, $i18n, $errorcode, $repeatable) { $MyException = New-Object System.Exception -ArgumentList ($exceptionText); $MyException.Data.Add("i18n", $i18n) $MyException.Data.Add("errorcode", $errorcode) $MyException.Data.Add("repeatable", $repeatable) return $MyException } <# Return Logeto scope value from system registry #> function Get-IsLogetoActiveHours { if (Test-LogetoRegistryValue $RegistryActiveHours $RegistryActiveHoursStartName) { $start = (Get-ItemProperty -Path $RegistryActiveHours -Name $RegistryActiveHoursStartName)."$RegistryActiveHoursStartName" Write-Host "Start is $start" } if (Test-LogetoRegistryValue $RegistryActiveHours $RegistryActiveHoursEndName) { $end = (Get-ItemProperty -Path $RegistryActiveHours -Name $RegistryActiveHoursEndName)."$RegistryActiveHoursEndName" Write-Host "End is $end" } if (($start) -And ($end)) { $currentHour = (Get-Date).Hour $currentMinutes = (Get-Date).Minute Write-Host "currentTime is $currentHour $currentMinutes" if (($currentHour -ge $start) -And (($currentHour -lt $end) -or (($currentHour -eq $end) -And ($currentMinutes -eq 0)))) { return $true } } return $false } <# Return Logeto scope value from system registry #> function Get-LogetoScope { if (Test-LogetoRegistryValue $RegistryFolder $RegistryScopeName) { $scope = (Get-ItemProperty -Path $RegistryFolder -Name $RegistryScopeName)."$RegistryScopeName" } elseif (Test-LogetoRegistryValue $RegistryFolderFallback $RegistryScopeName) { $scope = (Get-ItemProperty -Path $RegistryFolderFallback -Name $RegistryScopeName)."$RegistryScopeName" } if ($scope) { $scope = $scope.ToLower(); } return $scope } <# Test if registry key/name combination exists. #> Function Test-LogetoRegistryValue($regkey, $name) { Get-ItemProperty $regkey $name -ErrorAction SilentlyContinue | Out-Null $? } <# Extended Write-Host for installer purposes #> Function Write-LogetoProgress([String] $text, [String] $code) { if (Get-Command -CommandType Function -Name "Write-InstallerProgress" -ErrorAction SilentlyContinue) { Write-InstallerProgress $text $code } else { Write-Host $text } } <# Extended Write-Debug for installer purposes #> Function Write-LogetoDebug([String] $text) { if (Get-Command -CommandType Function -Name "Write-InstallerDebug" -ErrorAction SilentlyContinue) { Write-InstallerDebug $text } else { Write-Host $text } } function Get-IsElevated { return [bool](([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match "S-1-5-32-544") } function Get-IsFolderEmpty([String] $folder) { $c = (Get-ChildItem $folder) if ($c -eq $null) { return $true } else { return $false } } <# Extract zip file to destination directory #> Function Invoke-LogetoExtract($sourceFile, $destionationDir) { Write-LogetoProgress "Extract files to $destionationDir" "Invoke-LogetoExtract" if (Test-Path $destionationDir) { Remove-Item $destionationDir -Recurse -Force } if (!(Test-Path $destionationDir)) { New-Item -ItemType Directory -Force -Path $destionationDir | Out-Null } Add-Type -Assembly System.IO.Compression.FileSystem [System.IO.Compression.ZipFile]::ExtractToDirectory($sourceFile, $destionationDir) } Function Send-LogetoLogReport { Param( [parameter(Mandatory=$true)] $FunctionName, [parameter(Mandatory=$true)] $Exception ) try { $ehName = "logs" # hub name $ehNameSpace = "systemarteventhubs" # namespace $keyname = "PowershellSend" # name of the policy $key = "NpdfeCBfyJPyurG9EytYKtsDVXeecXCYDZA9DsjR6zk=" # Load the System.Web assembly to enable UrlEncode [Reflection.Assembly]::LoadWithPartialName("System.Web") | Out-Null $URI = "{0}.servicebus.windows.net/{1}" -f @($ehNameSpace,$ehName) $encodedURI = [System.Web.HttpUtility]::UrlEncode($URI) # Calculate expiry value one hour ahead $expiry = [string](([DateTimeOffset]::Now.ToUnixTimeSeconds())+3600) # Create the signature $stringToSign = [System.Web.HttpUtility]::UrlEncode($URI) + "`n" + $expiry $hmacsha = New-Object System.Security.Cryptography.HMACSHA256 $hmacsha.key = [Text.Encoding]::ASCII.GetBytes($key) $signature = $hmacsha.ComputeHash([Text.Encoding]::ASCII.GetBytes($stringToSign)) $signature = [System.Web.HttpUtility]::UrlEncode([Convert]::ToBase64String($signature)) # create Request Body $body = @{ Source="PS_PM" SourcePartition=$null LogType="Error" Timestamp=[System.DateTime]::UtcNow Message="Function: " + $FunctionName Exception=$Exception.Exception.Message } | ConvertTo-Json -Compress # API headers # $headers = @{ "Authorization"="SharedAccessSignature sr=" + $encodedURI + "&sig=" + $signature + "&se=" + $expiry + "&skn=" + $keyname; "Content-Type"="application/atom+xml;type=entry;charset=utf-8"; # must be this "Content-Length" = ("{0}" -f ($body.Length)) } # execute the Azure REST API $method = "POST" $dest = 'https://' +$URI +'/messages?timeout=60&api-version=2014-01' Invoke-RestMethod -Uri $dest -Method $method -Headers $headers -Body $body -Verbose } catch { try { # create Request Body $body = @{ Source="PS_PM" SourcePartition=$null LogType="Error" Timestamp=[System.DateTime]::UtcNow Message="Unable to send the log report in " + $FunctionName Exception=$null } | ConvertTo-Json -Compress # API headers # $headers = @{ "Authorization"="SharedAccessSignature sr=" + $encodedURI + "&sig=" + $signature + "&se=" + $expiry + "&skn=" + $keyname; "Content-Type"="application/atom+xml;type=entry;charset=utf-8"; # must be this "Content-Length" = ("{0}" -f ($body.Length)) } # execute the Azure REST API $method = "POST" $dest = 'https://' +$URI +'/messages?timeout=60&api-version=2014-01' Invoke-RestMethod -Uri $dest -Method $method -Headers $headers -Body $body -Verbose } catch {} } } |