# Define the MSP name [string]$Global:MSPName = "Emberkom" # This section will define several global variables that can be used in scripts that source this one [string]$Global:RootDirectory [string]$Global:ScriptsDirectory [string]$Global:OutputDirectory [string]$Global:ToolsDirectory [string]$Global:LogsDirectory [string]$Global:LogFile # Define the root path for the MSP in the Windows Registry [string]$Global:MSPRegistryRoot = "HKEY_LOCAL_MACHINE\SOFTWARE\${MSPName}" # Setup the MSP management directories Function Setup-MSPDirectories { If ( Test-Path ${Env:ProgramData} ) { $Global:RootDirectory = "${Env:ProgramData}\${MSPName}" } Else { $Global:RootDirectory = "${Env:SystemDrive}\${MSPName}" } $Global:ScriptsDirectory = "${RootDirectory}\Scripts" $Global:OutputDirectory = "${RootDirectory}\Output" $Global:ToolsDirectory = "${RootDirectory}\Tools" $Global:LogsDirectory = "${RootDirectory}\Logs" # Make sure all the management directories exist $RootDirectory, $ScriptsDirectory, $OutputDirectory, $ToolsDirectory, $LogsDirectory | ForEach-Object { If ( !(Test-Path $_) ) { Try { New-Item -Path $_ -ItemType Directory -Force -ErrorAction SilentlyContinue | Out-Null } Catch { Write-Output $_.Exception.Message } } } } # Function to get a datestamp for right now in a long format Function Get-LongDateTime { Return $(Get-Date -Format "yyyyMMddHHmmssffff") } # Setup the log file for messages generated when this script is run Function Setup-LogFile { $LogFilePrefix = "ManagementScript" $LogFilePostfix = Get-LongDateTime $Global:LogFile = "${LogsDirectory}\${LogFilePrefix}_${LogFilePostfix}.log" # Delete log files older than 120 days $LogFileAllowedAge = (Get-Date).AddDays(-120) Try { Get-ChildItem -Path "${LogsDirectory}\${LogFilePrefix}_*.*" -Filter '*.log' | ` Where-Object {$_.LastWriteTime -lt $LogFileAllowedAge} | ` Remove-Item -Force -ErrorAction SilentlyContinue | Out-Null } Catch { Write-Output $_.Exception.Message } Try { If ( !(Test-Path $LogFile) ) { New-Item -Path $LogFile -ItemType File -Force | Out-Null } } Catch { Write-Output $_.Exception.Message } } # Log a message to the log file # IMPORTANT: In Powershell 'echo' is an alias for Write-Output, which is overriden when this Tools.ps1 file is called before your script. # To prevent unwanted behavior, if you need to echo something do the following instead: # Start-Process "cmd.exe" -ArgumentList '/C echo y | some-command' Function Write-Output { param([Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$Message) Add-Content -Path $Global:LogFile -Value "$(Get-Date -Format "yyyy-MM-dd HH:mm:ss") - ${Message}" Microsoft.Powershell.Utility\Write-Output $Message } # Log an error to the log file Function Write-Error { param([Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$Message) Add-Content -Path $Global:LogFile -Value "$(Get-Date -Format "yyyy-MM-dd HH:mm:ss") - Error: ${Message}" Microsoft.Powershell.Utility\Write-Error $Message } # Function to determine if the current user context is an Administrator Function IsAdmin { If ( ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) ) { Return $true } Else { Return $false } } # Run a script from the live repo or from a local path Function Run-Script { param( # Parameters for live-ps scripts [Parameter(Mandatory=$false,ParameterSetName='live-ps')] [string]$Type='management-scripts', [Parameter(Mandatory=$true,ParameterSetName='live-ps')] [string]$LivePSScript, # Parameters for local scripts [Parameter(Mandatory=$true,ParameterSetName='local')] [string]$Path, ### $NoWait will prevent waiting for the specified script to finish running [Parameter(Mandatory=$false,ParameterSetName='local')] [switch]$NoWait=$false, # Parameters for all scripts [Parameter(Mandatory=$false,ParameterSetName='live-ps')] [Parameter(Mandatory=$false,ParameterSetName='local')] [string]$Arguments='null', ### $HaltIfRunning is a collection of app names which, if running, will prevent the script from running [Parameter(Mandatory=$false,ParameterSetName='live-ps')] [Parameter(Mandatory=$false,ParameterSetName='local')] [string[]]$HaltIfRunning='null', ### $ForceClose will forcefully close all apps specified in $HaltIfRunning [Parameter(Mandatory=$false,ParameterSetName='live-ps')] [Parameter(Mandatory=$false,ParameterSetName='local')] [switch]$ForceClose=$false ) If ( $Arguments -eq "null" ) { $Arguments = $null } If ( $HaltIfRunning -eq "null" ) { $HaltIfRunning = $null } If ( $LivePSScript ) { $URL = "https://dev.emberkom.com/emberkom/${Type}/raw/branch/master/${LivePSScript}.ps1" If ( !(IsURLValid -URL $URL) ) { Write-Output "The specified script does not exist: ${LivePSScript}" ; Exit } } If ( $Path ) { If ( !(Test-Path $Path) ) { Write-Output "The specified script does not exist: ""${Path}""" ; Exit } } If ( ($null -ne $HaltIfRunning ) -and ($ForceClose) -and ( !(IsAdmin) ) ) { Write-Output "Cannot close dependent apps because this task does not have administrative privileges" ; Exit } If ( $HaltIfRunning ) { $Halt = $false Write-Output "Checking for running instances of the following dependent apps:" ForEach ( $name in $HaltIfRunning) { $RunningInstances = Get-Process | Where-Object { $_.Name -like "${name}" } If ( $RunningInstances ) { If ( $ForceClose -eq $true ) { Try { $name | Stop-Process -Force ; Write-Output " ""${name}"" (force closed)" } Catch { Write-Error $_.Exception.Message ; Exit } } Else { $Halt = $true ; Write-Output " ""${name}"" (running)" } } Else { Write-Output " ""${name}"" (not running)" } } If ( $Halt -eq $true ) { Write-Output "Dependent apps are currently in use and are preventing the specified script from running" ; Exit } } switch ($PSCmdlet.ParameterSetName) { 'live-ps' { Write-Output "Retrieving : ${LivePSScript}.ps1" Try { $Script = (New-Object Net.WebClient).DownloadString($URL) } Catch { Write-Error $_.Exception.Message ; Exit } Try { $ScriptBlock = [Scriptblock]::Create($Script) } Catch { Write-Error $_.Exception.Message ; Exit } Write-Output "Executing: ${LivePSScript}.ps1 ${Arguments}" Try { Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments } Catch { Write-Error $_.Exception.Message ; Exit } } 'local' { Write-Output "Executing: ${Path} ${Arguments}" If ( $NoWait ) { Try { Start-Process "${Path}" -ArgumentList "{$Arguments}" } Catch { Write-Error $_.Exception.Message } } Else { Write-Output " Waiting for script to finish..." Try { Start-Process "${Path}" -ArgumentList "{$Arguments}" -Wait } Catch { Write-Error $_.Exception.Message } Write-Output " Finished" } } } } # Return a Powershell version object from a string Function Get-Version { param([Parameter(Mandatory=$true)][string]$Version) [int]$Sets = 4 $VersionArray = $Version.Split('.') If ( $VersionArray.Count -le $Sets ) { $Sets = $VersionArray.Count } For ($i = 0; $i -le ($Sets - 1); $i++) { $Return = '{0}.{1}' -f $Return, $VersionArray[$i] } Return [version]$Return.Trim('.') } # Determines whether a URL is valid Function IsURLValid { param([Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$URL) Try { $HTTPRequest = [System.Net.WebRequest]::Create($URL) $HTTPResponse = $HTTPRequest.GetResponse() $HTTPStatus = [int]$HTTPResponse.StatusCode $HTTPResponse.Close() } Catch { } If ($HTTPStatus -ne 404) { Return $true } Else { Return $false } } # Downloads a file from a URL Function Download-File { param( [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$URL, [Parameter(Mandatory=$false,ValueFromPipeline=$false)][string]$File ) If ( !($File) ) { $File = '{0}{1}' -f (Get-TempPath), (Split-Path $URL -Leaf) } If ( IsURLValid $URL ) { If ( Test-Path $File ) { Write-Output "Deleting existing file: ""${File}""" Try { Remove-Item $File -Force } Catch { Write-Error $_.Exception.Message } } Write-Output "Downloading ""${URL}"" to ""${File}""" Try { (New-Object System.Net.WebClient).DownloadFile($URL,$File) } Catch { Write-Error $_.Exception.Message } If ( Test-Path "${File}" ) { Return "${File}" } Else { Write-Output "Downloaded file does not exist at ""${File}""" ; Return $false } } Else { Write-Output "URL is not valid or file cannot be reached: ${URL}" } } # Install a program from a provided path Function Install-Program { param( [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$Path, [Parameter(Mandatory=$false)][string]$Arguments = '', [Parameter(Mandatory=$false)][switch]$Delete = $false ) If ( Test-Path "${Path}" ) { Write-Output "Running installer: ""${Path}"" ${Arguments}" Try { If ( $Arguments -eq '' ) { Start-Process "${Path}" -Wait } Else { Start-Process "${Path}" -ArgumentList "${Arguments}" -Wait } } Catch { Write-Error $_.Exception.Message } Write-Output "Installer finished" If ( $Delete ) { Write-Output "Deleting installer: ""${Path}""" Try { Remove-Item -Path "${Path}" -Force } Catch { Write-Error $_.Exception.Message } } } Else { Write-Output "The specified file could not be found: ""${Path}""" } } # Compare current Windows version with a supplied version # The value supplied must be a string and must include at least 1 decimal Function IsWindowsVersion { param( [Parameter(Mandatory=$true,ParameterSetName='gt')][string]$gt, [Parameter(Mandatory=$true,ParameterSetName='ge')][string]$ge, [Parameter(Mandatory=$true,ParameterSetName='lt')][string]$lt, [Parameter(Mandatory=$true,ParameterSetName='le')][string]$le, [Parameter(Mandatory=$true,ParameterSetName='eq')][string]$eq ) [version]$WindowsVersion = [System.Environment]::OSVersion.Version switch ($PSCmdlet.ParameterSetName) { 'gt' { If ( $WindowsVersion -gt (Get-Version $gt) ) { Return $true } Else { Return $false } } 'ge' { If ( $WindowsVersion -ge (Get-Version $ge) ) { Return $true } Else { Return $false } } 'lt' { If ( $WindowsVersion -lt (Get-Version $lt) ) { Return $true } Else { Return $false } } 'le' { If ( $WindowsVersion -le (Get-Version $le) ) { Return $true } Else { Return $false } } 'eq' { If ( $WindowsVersion -eq (Get-Version $eq) ) { Return $true } Else { Return $false } } } } # Compare current Windows build with a supplied version # The value supplied must be an int Function IsWindowsBuild { param( [Parameter(Mandatory=$true,ParameterSetName='gt')][int]$gt, [Parameter(Mandatory=$true,ParameterSetName='ge')][int]$ge, [Parameter(Mandatory=$true,ParameterSetName='lt')][int]$lt, [Parameter(Mandatory=$true,ParameterSetName='le')][int]$le, [Parameter(Mandatory=$true,ParameterSetName='eq')][int]$eq ) [int]$WindowsBuild = [System.Environment]::OSVersion.Version.Build switch ($PSCmdlet.ParameterSetName) { 'gt' { If ( $WindowsBuild -gt $gt ) { Return $true } Else { Return $false } } 'ge' { If ( $WindowsBuild -ge $ge ) { Return $true } Else { Return $false } } 'lt' { If ( $WindowsBuild -lt $lt ) { Return $true } Else { Return $false } } 'le' { If ( $WindowsBuild -le $le ) { Return $true } Else { Return $false } } 'eq' { If ( $WindowsBuild -eq $eq ) { Return $true } Else { Return $false } } } } # Get the path to the TEMP folder (context dependent) Function Get-TempPath { Return [System.IO.Path]::GetTempPath() } # Determine if the system is 64-bit or not Function Is64bit { switch ( $(Get-CimInstance -ClassName Win32_OperatingSystem -Property OSArchitecture | Select-Object -ExpandProperty OSArchitecture) ) { '64-bit' { Return $true } '32-bit' { Return $false } } } # Determine if the Powershell process is 64-bit or not Function Is64bitShell { If ( [System.Environment]::Is64BitProcess ) { Return $true } Else { Return $false } } # Determine if a user is in a built-in role or specified group Function IsMemberOf { param( [Parameter(Mandatory=$false)] [switch]$Builtin=$false, [Parameter(Mandatory=$true,ValueFromPipeline=$true)] [string]$Group ) If ( $Builtin ) { Switch ( $Group ) { ("Administrator" -or "Administrators") { $Group = [System.Security.Principal.WindowsBuiltInRole]::Administrator ; Break } ("Backup Operator" -or "Backup Operators" -or "BackupOperator" -or "BackupOperators") { $Group = [System.Security.Principal.WindowsBuiltInRole]::BackupOperator ; Break } ("System Operator" -or "System Operators" -or "SystemOperator" -or "SystemOperators") { $Group = [System.Security.Principal.WindowsBuiltInRole]::SystemOperator ; Break } ("Account Operator" -or "Account Operators" -or "AccountOperator" -or "AccountOperators") { $Group = [System.Security.Principal.WindowsBuiltInRole]::AccountOperator ; Break } ("Print Operator" -or "Print Operators" -or "PrintOperator" -or "PrintOperators") { $Group = [System.Security.Principal.WindowsBuiltInRole]::PrintOperator ; Break } ("Replicator" -or "Replicators") { $Group = [System.Security.Principal.WindowsBuiltInRole]::Replicator ; Break } ("Power User" -or "Power Users" -or "PowerUser" -or "PowerUsers") { $Group = [System.Security.Principal.WindowsBuiltInRole]::PowerUser ; Break } ("User" -or "Users") { $Group = [System.Security.Principal.WindowsBuiltInRole]::User ; Break } ("Guest" -or "Guests") { $Group = [System.Security.Principal.WindowsBuiltInRole]::Guest ; Break } default { ; Break } } } Return ([Security.Principal.WindowsPrincipal][System.Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole($Group) } # Start, stop, restart, or delete a list of services Function Control-Service { param( [Parameter(Mandatory=$true,ParameterSetName='start')] [switch]$Start, [Parameter(Mandatory=$true,ParameterSetName='stop')] [switch]$Stop, [Parameter(Mandatory=$true,ParameterSetName='restart')] [switch]$Restart, [Parameter(Mandatory=$true,ParameterSetName='delete')] [switch]$Delete, [Parameter(Mandatory=$true,ParameterSetName='disable')] [switch]$Disable, [Parameter(Mandatory=$true,ValueFromPipeline=$true,ParameterSetName='start')] [Parameter(Mandatory=$true,ValueFromPipeline=$true,ParameterSetName='stop')] [Parameter(Mandatory=$true,ValueFromPipeline=$true,ParameterSetName='restart')] [Parameter(Mandatory=$true,ValueFromPipeline=$true,ParameterSetName='delete')] [Parameter(Mandatory=$true,ValueFromPipeline=$true,ParameterSetName='disable')] [string[]]$Name, [Parameter(Mandatory=$false,ParameterSetName='start')] [Parameter(Mandatory=$false,ParameterSetName='stop')] [Parameter(Mandatory=$false,ParameterSetName='restart')] [Parameter(Mandatory=$false,ParameterSetName='delete')] [Parameter(Mandatory=$false,ParameterSetName='disable')] [switch]$Match=$false ) switch ($PSCmdlet.ParameterSetName) { 'start' { $statuscondition = 'Running' $verb = 'start' $verbing = 'Starting' } 'stop' { $statuscondition = 'Stopped' $verb = 'stop' $verbing = 'Stopping' } 'restart' { $ArgString = $MyInvocation.Line $StopCmd = $ArgString -replace ' -Restart ', ' -Stop ' $StartCmd = $ArgString -replace ' -Restart ', ' -Start ' Invoke-Expression $StopCmd Invoke-Expression $StartCmd Exit } 'delete' { # Delete the service } 'disable' { $ArgString = $MyInvocation.Line $StopCmd = $ArgString -replace ' -Disable ', ' -Stop ' Invoke-Expression $StopCmd $statuscondition = 'Disabled' $verb = 'disable' $verbing = 'Disabling' } } ForEach ( $item in $Name ) { $service = Get-Service -Name $item -ErrorAction SilentlyContinue If ( !($service) ) { Write-Output "Cannot find the service '${item}'" If ( $Match ) { Write-Output "Attempting to match '${item}' to service display names" ForEach ( $svc in ((Get-Service | Where-Object { $_.DisplayName -match $item }).Name) ) { Switch ( $verb) { 'start' { Control-Service -Start -Name $svc } 'stop' { Control-Service -Stop -Name $svc } 'disable' { Control-Service -Disable -Name $svc } } } } } Else { $name = $service.Name $fullname = $service.DisplayName If ( ([string]::IsNullOrEmpty($fullname)) -or ($fullname -eq $name) ) { $displayname = "'${name}'" } Else { $displayname = """${fullname}"" (${name})" } If ( $service.Status -ne $statuscondition ) { Write-Output "${verbing} ${displayname}" Try { Switch ( $verb) { 'start' { Start-Service -Name $name } 'stop' { Stop-Service -Name $name -Force } 'disable' { Set-Service -Name "${name}" -StartupType Disabled } } } Catch { Write-Error $_.Exception.Message } } } } } # Stop a process Function End-Process { param( [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string[]]$Name, [Parameter(Mandatory=$false)][switch]$Match=$false, [Parameter(Mandatory=$false)][switch]$Force=$false ) ForEach ( $item in $Name ) { $process = Get-Process -Name $item -ErrorAction SilentlyContinue If ( !($process) ) { Write-Output "Cannot find the process '${item}'" If ( $Match ) { Write-Output "Attempting to match '${item}' to all running process names" ForEach ( $proc in ((Get-Process | Where-Object { $_.Name -match $item }).Name) ) { If ( $Force ) { End-Process -Name $proc -Force } Else { End-Process -Name $proc } } } } Else { $name = $process.Name If ( $Force ) { Write-Output "Forcefully stopping '${name}' process" Stop-Process $process -Force -ErrorAction SilentlyContinue } Else { Write-Output "Attempting to gracefully close '${name}' process" $process.CloseMainWindow() | Out-Null } } } } Function Create-Shortcut { param( [Parameter(Mandatory=$true)][string]$Path, [Parameter(Mandatory=$true)][string]$TargetPath, [Parameter(Mandatory=$false)][string]$Arguments, [Parameter(Mandatory=$false)][string]$Description, [Parameter(Mandatory=$false)][string]$Icon = '', [Parameter(Mandatory=$false)][string]$WorkingDirectory = '' ) If ( Test-Path $TargetPath ) { If ( Test-Path $Path ) { Write-Output "Deleting existing shortcut at ""${Path}""" Try { Remove-Item $Path -Force -ErrorAction SilentlyContinue } Catch { Write-Error $_.Exception.Message } } If ( $WorkingDirectory -eq '' ) { $WorkingDirectory = Split-Path $TargetPath -Parent } If ( $Icon -eq '' ) { $Icon = "${TargetPath}, 0" } $WshShell = New-Object -ComObject WScript.Shell $Shortcut = $WshShell.CreateShortcut($Path) $Shortcut.Arguments = $Arguments $Shortcut.Description = $Description $Shortcut.IconLocation = $Icon $Shortcut.WorkingDirectory = $WorkingDirectory $Shortcut.TargetPath = $TargetPath Write-Output "Creating shortcut to ""${TargetPath}"" at ""${Path}""" Try { $Shortcut.Save() } Catch { Write-Error $_.Exception.Message } } Else { Write-Output "Cannot create shortcut because the target path does not exist" } } # Function to enable or disable a specified log Function Toggle-Log { param ( [Parameter(Mandatory = $true)][string]$Name, [Parameter(Mandatory = $true, ParameterSetName = 'Enable')][switch]$Enable, [Parameter(Mandatory = $true, ParameterSetName = 'Disable')][switch]$Disable ) Try { $log = New-Object System.Diagnostics.Eventing.Reader.EventLogConfiguration $Name If ( $Enable ) { Write-Output "Enabing ${Name} event log" ; $log.IsEnabled = $true } If ( $Disable ) { Write-Output "Disabing ${Name} event log" ; $log.IsEnabled = $false } $log.SaveChanges() } Catch { Write-Output $_.Exception.Message } } # Function to install the PSAtera Powershell module Function Install-PSAteraModule { Try { $module = Get-Module -ListAvailable -Name PSAtera If ( (-not $module) -and (IsAdmin) ) { Write-Output "Installing PSAtera Powershell module" Install-Module -Name PSAtera -Force } ElseIf ( (-not $module) -and (-not (IsAdmin)) ) { Write-Output "The PSAtera module needs to be installed, but the current security context is not sufficient to install it" } } Catch { Write-Error $_.Exception.Message } } # Function to install the MSP360 Powershell module Function Install-MSP360Module { Try { $module = Get-Module -ListAvailable -Name MSP360 If ( (-not $module) -and (IsAdmin) ) { Write-Output "Installing MSP360 Powershell module" Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope Process [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; Invoke-Expression (New-Object System.Net.WebClient).DownloadString('https://git.io/JUSAA'); Install-MSP360Module } ElseIf ( (-not $module) -and (-not (IsAdmin)) ) { Write-Output "The MSP360 Powershell module needs to be installed, but the current security context is not sufficient to install it" } } Catch { Write-Error $_.Exception.Message } } # Function to delete a file Function Remove-File ([Parameter(ValueFromPipeline=$true)][string]$path) { If ( Test-Path $path ) { If ( !((Get-Item $path) -is [System.IO.DirectoryInfo]) ) { Try { Write-Output "Delete ""${path}""" Remove-Item $path -Force } Catch { Write-Error $_.Exception.Message } } } } # Function to ZIP a file or directory Function Zip-Object { param( [Parameter(ValueFromPipeline=$true)][string]$path, [Parameter(ValueFromPipeline=$false)][string]$dest ) If ( $(Get-Item $path) -is [System.IO.DirectoryInfo] ) { If ( [string]::IsNullOrEmpty($dest) ) { $dest = '{0}\{1}.zip' -f $(Split-Path -Parent $path),$(Split-Path -Leaf $path) } Write-Output "Creating zip file of: ${path}" Try { Add-Type -Assembly "System.IO.Compression.FileSystem" [IO.Compression.ZipFile]::CreateFromDirectory($path, $dest) } Catch { Write-Error $_.Exception.Message } If ( Test-Path $dest ) { Return $dest } Else { Return $false } } ElseIf ( $(Get-Item $path) -is [System.IO.FileInfo] ) { $dir = $path.Substring(0, $path.LastIndexOf('.')) Try { Write-Output "Creating directory: ${path}" New-Item -ItemType Directory -Path $dir -ErrorAction Stop | Out-Null Write-Output "Moving ""${path}"" into ""${dir}""" Move-Item -Path $path -Destination $dir -Force -ErrorAction Stop | Out-Null } Catch { Write-Error $_.Exception.Message } Zip-Object $dir } Else { Write-Output "Could not determine the file/folder status: ${path}" } } # Function to UNZIP a file or directory Function Unzip-Object ([Parameter(ValueFromPipeline=$true)][string]$path) { If ( [System.IO.Path]::GetExtension($path) -eq ".zip" ) { $dest = Split-Path -Parent $path Write-Output "Extracting ""${path}"" to ""${dest}""" Try { Add-Type -Assembly "System.IO.Compression.FileSystem" [IO.Compression.ZipFile]::ExtractToDirectory($path, $dest) } Catch { Write-Error $_.Exception.Message } } Else { Write-Output "The path specified is not a zip file: ${path}" } } # Function to get a copy of the LiquidFiles CLI agent Function Get-LiquidFilesCLI { $url = 'https://lfupdate.s3.amazonaws.com/clients/windows_cli/LiquidFilesCLI-2.0.128.zip' $zip_filename = Split-Path -Leaf $url $zip_path = "${Global:ToolsDirectory}\${zip_filename}" $exe_path = '{0}\{1}.exe' -f $Global:ToolsDirectory,[System.IO.Path]::GetFileNameWithoutExtension($zip_filename) If ( Test-Path $zip_path ) { Write-Output "Deleting existing zip archive: ${zip_path}" Try { Remove-Item -Path $zip_path -Force } Catch { Write-Error $_.Exception.Message } } If ( Test-Path $exe_path ) { Write-Output "Deleting existing file: ${exe_path}" Try { Remove-Item -Path $exe_path -Force } Catch { Write-Error $_.Exception.Message } } Download-File -URL $url -File $zip_path | Out-Null Unzip-Object $zip_path Return $exe_path } # Function to determine if an app is running Function IsRunning ([Parameter(ValueFromPipeline=$true)][string]$Name) { $RunningInstances = Get-Process | Where-Object { $_.Name -ilike $Name } If ( $RunningInstances ) { Return $true } Else { Return $false } } # Function to create a local user account Function Create-LocalUser { param( [Parameter(Mandatory=$true)][string]$Username, [Parameter(Mandatory=$true)][string]$Password, [Parameter(Mandatory=$true)][string]$FullName, [Parameter(Mandatory=$true)][string]$Description, [Parameter(Mandatory=$false)][switch]$MakeAdmin=$false, [Parameter(Mandatory=$false)][switch]$Hide=$false ) # Secure supplied password Try { $SecurePassword = ConvertTo-SecureString $Password -AsPlainText -Force ; $Password = $null } Catch { Write-Error $_.Exception.Message ; Exit } If ( IsAdmin ) { If ( $(Get-CimInstance -ClassName Win32_OperatingSystem -Property ProductType | Select-Object -ExpandProperty ProductType) -ne "2" ) { If ( $(Get-LocalUser -Name $Username -ErrorAction SilentlyContinue) ) { Write-Output "Updating user: ${Username}" Try { Set-LocalUser -Name $Username -Password $SecurePassword -FullName $FullName -Description $Description -AccountNeverExpires -PasswordNeverExpires } Catch { Write-Error $_.Exception.Message ; Exit } } Else { Write-Output "Creating user: ${Username}" Try { New-LocalUser -Name $Username -Password $SecurePassword -FullName $FullName -Description $Description -AccountNeverExpires -PasswordNeverExpires } Catch { Write-Error $_.Exception.Message ; Exit } } If ( (-not($(Get-LocalGroupMember -Group "Administrators" -Member $Username -ErrorAction SilentlyContinue))) -and $MakeAdmin ) { Write-Output "Adding ""${Username}"" to local Administrators group" Try { Add-LocalGroupMember -Name "Administrators" -Member $(Get-LocalUser -Name $Username) } Catch { Write-Error $_.Exception.Message ; Exit } } } Else { Write-Output "Cannot create or modify local accounts on a domain controller" } } Else { Write-Output "Cannot create or modify a local account without administrative privileges" } If ( $Hide ) { # TODO: Hide account from logon screen #Get-ChildItem "HKLM:SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts\UserList" } } # Returns the number of MB a process is consuming Function Get-MemoryUsage ([string]$AppName) { [math]::Round((Get-Process -Name $AppName -ErrorAction SilentlyContinue | Measure-Object -Property WorkingSet -Sum).Sum / 1MB) } # Kills a process if it's using more than the specified amount of memory Function Stop-MemoryHog ([string]$AppName,[int]$MemoryLimit) { $MemoryUsed = (Get-MemoryUsage -AppName $AppName) If ( $MemoryUsed -gt $MemoryLimit ) { $MemoryDifference = $MemoryUsed - $MemoryLimit Write-Output "Killing ""${AppName}"" for using ${MemoryDifference}MB over the limit of ${MemoryLimit}MB" Try { Get-Process -Name $AppName -ErrorAction SilentlyContinue | Stop-Process -Force } Catch { Write-Error $_.Exception.Message } } } # Returns a formatted list of the largest or smallest files in a directory Function Get-FileSizes { param( [Parameter(ValueFromPipeline=$true)][string]$Path, [switch]$Recurse, [switch]$IncludeHidden, [Parameter(ParameterSetName="largest")][int]$Largest, [Parameter(ParameterSetName="smallest")][int]$Smallest, [string]$Units, [int]$Precision=2 ) # If no path is specified, set $Path to the directory containing user profiles If (-not $Path ) { $Path = (Get-ItemPropertyValue -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList' -Name ProfilesDirectory) $Recurse = $true $IncludeHidden = $false } # Change the sort order depending on which parameter set was specified Switch ( $PSCmdlet.ParameterSetName ) { "largest" { $SortOrder = $true ; $Quantity = $Largest } "smallest" { $SortOrder = $false ; $Quantity = $Smallest } } # Set the units to show sizes in output Switch ( $Units.ToUpper() ) { "KB" { $UnitLabel = "Kilobytes (KB)" ; $Divisor = 1KB } "MB" { $UnitLabel = "Megabytes (MB)" ; $Divisor = 1MB } "GB" { $UnitLabel = "Gigabytes (GB)" ; $Divisor = 1GB } "TB" { $UnitLabel = "Terabytes (TB)" ; $Divisor = 1TB } default { $UnitLabel = "Bytes" ; $Divisor = 1 } } # Get the file paths and sizes as specified $FileSizes = Get-ChildItem $Path -Recurse:$Recurse -Force:$IncludeHidden -ErrorAction SilentlyContinue | Sort-Object -Descending:$SortOrder -Property Length | Select-Object -First $Quantity @{Name="File Path";Expression={$_.DirectoryName + '\' + $_.Name}}, @{Name=$UnitLabel;Expression={[Math]::Round($_.Length / $Divisor, $Precision)}} # Set output prefix $prefix = "The ${Quantity} " + $PSCmdlet.ParameterSetName + " files found at ""${Path}""" # Output to console $constr = "${prefix}" + $($FileSizes | Out-String) Write-Output $constr # Output to log file $logstr = "${prefix}" + $($FileSizes | Format-List | Out-String) Write-Output $logstr } # Function to write text to a file in UTF8 encoding without BOM Function WriteToFile_UTF8NoBOM { param( [Parameter(ValueFromPipeline=$false)][string]$FilePath, [Parameter(ValueFromPipeline=$true)][string]$Value ) $UTF8NoBOM = New-Object System.Text.UTF8Encoding $false Try { [IO.File]::WriteAllText($FilePath, $CONFIG, $UTF8NoBOM) } Catch { Write-Error $_.Exception.Message } } # Function to enumerate all user profile folders Function EnumUserProfiles { $ProfilePath = (Get-ItemPropertyValue -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList' -Name ProfilesDirectory) $UserProfilePaths = @() ForEach ( $userProfile in (Get-ChildItem -Path $ProfilePath | Where-Object { $_.PSIsContainer }) ) { $UserProfilePaths += ,@($userProfile.FullName) } Return $UserProfilePaths } # Function to test for the presense of a Registry property Function Test-RegistryProperty { param( [Parameter(Mandatory=$true)][string]$Path, [Parameter(Mandatory=$true)][string]$Name ) Try { Get-ItemProperty -Path $Path | Select-Object -ExpandProperty $Name -ErrorAction Stop | Out-Null Return $true } Catch { Return $false } } # Function to format a quantity of bytes into a denomination Function Beautify-Bytes { param( [int64]$Amount, [int]$Precision=2, [string]$Units, [switch]$WithUnitLabel ) Switch ( $Units.ToUpper() ) { "KB" { $UnitLabel = "KB" ; $Divisor = 1KB } "MB" { $UnitLabel = "MB" ; $Divisor = 1MB } "GB" { $UnitLabel = "GB" ; $Divisor = 1GB } "TB" { $UnitLabel = "TB" ; $Divisor = 1TB } default { $UnitLabel = "bytes" ; $Divisor = 1 } } Switch ( $WithUnitLabel ) { $true { Return (ZeroPad-Decimal -Amount $([Math]::Round($Amount / $Divisor,$Precision)) -NeededDecimalPlaces $Precision) + "${UnitLabel}" } $false { Return (ZeroPad-Decimal -Amount $([Math]::Round($Amount / $Divisor,$Precision)) -NeededDecimalPlaces $Precision) } } } # Function to pad zeros onto the end of a decimal number Function ZeroPad-Decimal { param( $Amount, $NeededDecimalPlaces ) $splitNumbers = $Amount.ToString().Split('.') $paddedDecimal = $splitNumbers[1].PadRight($NeededDecimalPlaces, '0') Return $splitNumbers[0] + '.' + $paddedDecimal } # Function to follow a URL and return the absolute URI of the result (whether redirected or not) Function Get-AbsoluteURI { param([string]$URL) Return [System.Net.HttpWebRequest]::Create($URL).GetResponse().ResponseUri.AbsoluteUri } Function Get-GUIDFromMSIUninstallString ([string]$str) { $start = $str.IndexOf('{') + 1 $end = $str.IndexOf('}') $retval = $str.Substring($start, $end - $start) If ( $retval.Length -ne 36 ) { $retval = $null } Return $retval } Function Uninstall-MSI ([Parameter(ValueFromPipeline=$true)][string[]]$APP_NAMES) { PROCESS { # Get all of the uninstall registry keys $UNINSTALL_KEYS = Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall -ErrorAction SilentlyContinue $UNINSTALL_KEYS += Get-ChildItem -Path HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall -ErrorAction SilentlyContinue # Exit if we can't find any software at all If ( $UNINSTALL_KEYS.Length -eq 0 ) { Write-Error "Attempted to uninstall ${APP_NAMES} but could not find any installed apps in the Windows Registry" ; Return } # Array to store custom objects about each installed MSI app $INSTALLED_APPS = @() Foreach ( $reg in $UNINSTALL_KEYS ) { # Get the uninstall key $REG_PROPERTY = Get-ItemProperty -Path $reg.PSPath # Guards to prevent working with incompatible apps If ( [string]::IsNullOrEmpty($REG_PROPERTY.UninstallString) -and [string]::IsNullOrEmpty($REG_PROPERTY.ModifyPath) ) { Continue } # Determine if the app is installed via MSI If ( $REG_PROPERTY.WindowsInstaller -eq 1 ) { $UNINSTALL_SUPPORTED = $true } Else { $UNINSTALL_SUPPORTED = $false } # Get the product code from the UninstallString or ModifyPath if the app is installed via MSI [string]$PRODUCT_CODE = $null If ( ![string]::IsNullOrEmpty($REG_PROPERTY.UninstallString) -and $UNINSTALL_SUPPORTED ) { $PRODUCT_CODE = $(Get-GUIDFromMSIUninstallString -str $REG_PROPERTY.UninstallString) } # Get the product code from the ModifyPath ElseIf ( ![string]::IsNullOrEmpty($REG_PROPERTY.ModifyPath) -and $UNINSTALL_SUPPORTED ) { $PRODUCT_CODE = $(Get-GUIDFromMSIUninstallString -str $REG_PROPERTY.ModifyPath) } # Additional guard to prevent adding an app with no product code If ( [string]::IsNullOrEmpty($PRODUCT_CODE) ) { Continue } $customObject = [PSCustomObject]@{ UninstallSupported = $UNINSTALL_SUPPORTED DisplayName = $REG_PROPERTY.DisplayName UninstallString = $REG_PROPERTY.UninstallString ModifyPath = $REG_PROPERTY.ModifyPath ProductCode = $PRODUCT_CODE } $INSTALLED_APPS += $customObject } Foreach ( $app in $APP_NAMES ) { Foreach ( $installed_app in $INSTALLED_APPS ) { # Make sure the DisplayName matches what we're looking for If ( !($installed_app.DisplayName -ilike $app) ) { Continue } $DisplayName = $installed_app.DisplayName $UninstallString = $installed_app.UninstallString $ProductCode = $installed_app.ProductCode # Print out uninstall string for unsupported apps If ( $installed_app.UninstallSupported -eq $false ) { Write-Output "Cannot uninstall ""${DisplayName}""`n UninstallString: ${UninstallString}" Continue } # Uninstall the app Write-Output "Uninstalling ""${DisplayName}"" with product code: ${ProductCode}" $arguments = '/X{' + $ProductCode + '} /qn /norestart' Try { Start-Process -FilePath "msiexec.exe" -ArgumentList $arguments -Wait } Catch { Write-Error $_.Exception.Message } } } } } # Reboot an endpoint based on the amount of time it has been running without a reboot Function Restart-EndpointOnUptime ([timespan]$MaxUptime) { # Get the length of time the endpoint has been running without restart Try { $LastBootTime = (Get-CimInstance -ClassName Win32_OperatingSystem -ErrorAction Stop).LastBootUpTime } Catch { Write-Error $_.Exception.Message ; Exit } # Get the difference between the endpoint uptime and the current time $Delta = New-TimeSpan -Start $LastBootTime -End $(Get-Date) # Stop the function if the endpoint has not exceeded $MaxUptime If ( $Delta -lt $MaxUptime ) { Exit } # Reboot the endpoint Try { Restart-Computer -Force -ErrorAction Stop } Catch { Write-Error $_.Exception.Message } } Setup-MSPDirectories Setup-LogFile #SetToolsScriptLocation