major update to override Write-Output func
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
## Define the MSP name
|
||||
# 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
|
||||
# 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
|
||||
@@ -12,7 +12,7 @@
|
||||
# Define the root path for the MSP in the Windows Registry
|
||||
[string]$Global:MSPRegistryRoot = "HKEY_LOCAL_MACHINE\SOFTWARE\${MSPName}"
|
||||
|
||||
## Setup the MSP management directories
|
||||
# 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"
|
||||
@@ -20,7 +20,7 @@ Function Setup-MSPDirectories {
|
||||
$Global:ToolsDirectory = "${RootDirectory}\Tools"
|
||||
$Global:LogsDirectory = "${RootDirectory}\Logs"
|
||||
|
||||
## Make sure all the management directories exist
|
||||
# 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 }
|
||||
@@ -29,18 +29,18 @@ Function Setup-MSPDirectories {
|
||||
}
|
||||
}
|
||||
|
||||
## Function to get a datestamp for right now in a long format
|
||||
# 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
|
||||
# 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
|
||||
# Delete log files older than 120 days
|
||||
$LogFileAllowedAge = (Get-Date).AddDays(-120)
|
||||
Try {
|
||||
Get-ChildItem -Path "${LogsDirectory}\${LogFilePrefix}_*.*" -Filter '*.log' | `
|
||||
@@ -53,51 +53,51 @@ Function Setup-LogFile {
|
||||
Catch { Write-Output $_.Exception.Message }
|
||||
}
|
||||
|
||||
## Log a message to the log file
|
||||
Function LogMsg {
|
||||
# Log a message to the log file
|
||||
Function Write-Output {
|
||||
param([Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$Message)
|
||||
$Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
|
||||
$LogEntry = "${Timestamp} - ${Message}"
|
||||
Add-Content -Path $Global:LogFile -Value $LogEntry
|
||||
}
|
||||
|
||||
## Log an error to the log file
|
||||
Function LogErr {
|
||||
# Log an error to the log file
|
||||
Function Write-Error {
|
||||
param([Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$Message)
|
||||
$Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
|
||||
$LogEntry = "${Timestamp} - Error: ${Message}"
|
||||
Add-Content -Path $Global:LogFile -Value $LogEntry
|
||||
}
|
||||
|
||||
## Function to determine if the current user context is an Administrator
|
||||
# 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
|
||||
# Run a script from the live repo or from a local path
|
||||
Function Run-Script {
|
||||
param(
|
||||
## Parameters for live-ps scripts
|
||||
# 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
|
||||
# Parameters for local scripts
|
||||
[Parameter(Mandatory=$true,ParameterSetName='local')]
|
||||
[string]$Path,
|
||||
#### $NoWait will prevent waiting for the specified script to finish running
|
||||
### $NoWait will prevent waiting for the specified script to finish running
|
||||
[Parameter(Mandatory=$false,ParameterSetName='local')]
|
||||
[switch]$NoWait=$false,
|
||||
## Parameters for all scripts
|
||||
# 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
|
||||
### $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
|
||||
### $ForceClose will forcefully close all apps specified in $HaltIfRunning
|
||||
[Parameter(Mandatory=$false,ParameterSetName='live-ps')]
|
||||
[Parameter(Mandatory=$false,ParameterSetName='local')]
|
||||
[switch]$ForceClose=$false
|
||||
@@ -106,63 +106,63 @@ Function Run-Script {
|
||||
If ( $HaltIfRunning -eq "null" ) { $HaltIfRunning = $null }
|
||||
If ( $LivePSScript ) {
|
||||
$URL = "https://dev.emberkom.com/emberkom/${Type}/raw/branch/master/${LivePSScript}.ps1"
|
||||
If ( !(IsURLValid -URL $URL) ) { LogMsg "The specified script does not exist: ${LivePSScript}" ; Exit }
|
||||
If ( !(IsURLValid -URL $URL) ) { Write-Output "The specified script does not exist: ${LivePSScript}" ; Exit }
|
||||
}
|
||||
If ( $Path ) { If ( !(Test-Path $Path) ) { LogMsg "The specified script does not exist: ""${Path}""" ; Exit } }
|
||||
If ( ($null -ne $HaltIfRunning ) -and ($ForceClose) -and ( !(IsAdmin) ) ) { LogMsg "Cannot close dependent apps because this task does not have administrative privileges" ; 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
|
||||
LogMsg "Checking for running instances of the following dependent apps:"
|
||||
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 ; LogMsg " ""${name}"" (force closed)" }
|
||||
Catch { LogErr $_.Exception.Message ; Exit }
|
||||
Try { $name | Stop-Process -Force ; Write-Output " ""${name}"" (force closed)" }
|
||||
Catch { Write-Error $_.Exception.Message ; Exit }
|
||||
}
|
||||
Else { $Halt = $true ; LogMsg " ""${name}"" (running)" }
|
||||
Else { $Halt = $true ; Write-Output " ""${name}"" (running)" }
|
||||
}
|
||||
Else { LogMsg " ""${name}"" (not running)" }
|
||||
Else { Write-Output " ""${name}"" (not running)" }
|
||||
}
|
||||
If ( $Halt -eq $true ) { LogMsg "Dependent apps are currently in use and are preventing the specified script from running" ; Exit }
|
||||
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' {
|
||||
LogMsg "Retrieving : ${LivePSScript}.ps1"
|
||||
Write-Output "Retrieving : ${LivePSScript}.ps1"
|
||||
Try { $Script = (New-Object Net.WebClient).DownloadString($URL) }
|
||||
Catch { LogErr $_.Exception.Message ; Exit }
|
||||
Catch { Write-Error $_.Exception.Message ; Exit }
|
||||
Try { $ScriptBlock = [Scriptblock]::Create($Script) }
|
||||
Catch { LogErr $_.Exception.Message ; Exit }
|
||||
LogMsg "Executing: ${LivePSScript}.ps1 ${Arguments}"
|
||||
Catch { Write-Error $_.Exception.Message ; Exit }
|
||||
Write-Output "Executing: ${LivePSScript}.ps1 ${Arguments}"
|
||||
Try { Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments }
|
||||
Catch { LogErr $_.Exception.Message ; Exit }
|
||||
Catch { Write-Error $_.Exception.Message ; Exit }
|
||||
}
|
||||
|
||||
'local' {
|
||||
LogMsg "Executing: ${Path} ${Arguments}"
|
||||
Write-Output "Executing: ${Path} ${Arguments}"
|
||||
If ( $NoWait ) {
|
||||
Try { Start-Process "${Path}" -ArgumentList "{$Arguments}" }
|
||||
Catch { LogErr $_.Exception.Message }
|
||||
Catch { Write-Error $_.Exception.Message }
|
||||
}
|
||||
Else {
|
||||
LogMsg " Waiting for script to finish..."
|
||||
Write-Output " Waiting for script to finish..."
|
||||
Try { Start-Process "${Path}" -ArgumentList "{$Arguments}" -Wait }
|
||||
Catch { LogErr $_.Exception.Message }
|
||||
LogMsg " Finished"
|
||||
Catch { Write-Error $_.Exception.Message }
|
||||
Write-Output " Finished"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$LogFileContent = (Get-Content $LogFile)
|
||||
|
||||
## Write the log file output to the console
|
||||
# Write the log file output to the console
|
||||
If ( $LogFileContent ) { Write-Output $LogFileContent }
|
||||
|
||||
## Delete the log file if it's empty
|
||||
# Delete the log file if it's empty
|
||||
Else { Remove-Item $LogFile -Force }
|
||||
}
|
||||
|
||||
## Return a Powershell version object from a string
|
||||
# Return a Powershell version object from a string
|
||||
Function Get-Version {
|
||||
param([Parameter(Mandatory=$true)][string]$Version)
|
||||
[int]$Sets = 4
|
||||
@@ -173,7 +173,7 @@ Function Get-Version {
|
||||
Return [version]$Return.Trim('.')
|
||||
}
|
||||
|
||||
## Determines whether a URL is valid
|
||||
# Determines whether a URL is valid
|
||||
Function IsURLValid {
|
||||
param([Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$URL)
|
||||
Try {
|
||||
@@ -187,7 +187,7 @@ Function IsURLValid {
|
||||
Else { Return $false }
|
||||
}
|
||||
|
||||
## Downloads a file from a URL
|
||||
# Downloads a file from a URL
|
||||
Function Download-File {
|
||||
param(
|
||||
[Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$URL,
|
||||
@@ -196,20 +196,20 @@ Function Download-File {
|
||||
If ( !($File) ) { $File = '{0}{1}' -f (Get-TempPath), (Split-Path $URL -Leaf) }
|
||||
If ( IsURLValid $URL ) {
|
||||
If ( Test-Path $File ) {
|
||||
LogMsg "Deleting existing file: ""${File}"""
|
||||
Write-Output "Deleting existing file: ""${File}"""
|
||||
Try { Remove-Item $File -Force }
|
||||
Catch { LogErr $_.Exception.Message }
|
||||
Catch { Write-Error $_.Exception.Message }
|
||||
}
|
||||
LogMsg "Downloading ""${URL}"" to ""${File}"""
|
||||
Write-Output "Downloading ""${URL}"" to ""${File}"""
|
||||
Try { (New-Object System.Net.WebClient).DownloadFile($URL,$File) }
|
||||
Catch { LogErr $_.Exception.Message }
|
||||
Catch { Write-Error $_.Exception.Message }
|
||||
If ( Test-Path "${File}" ) { Return "${File}" }
|
||||
Else { LogMsg "Downloaded file does not exist at ""${File}""" ; Return $false }
|
||||
Else { Write-Output "Downloaded file does not exist at ""${File}""" ; Return $false }
|
||||
}
|
||||
Else { LogMsg "URL is not valid or file cannot be reached: ${URL}" }
|
||||
Else { Write-Output "URL is not valid or file cannot be reached: ${URL}" }
|
||||
}
|
||||
|
||||
## Install a program from a provided path
|
||||
# Install a program from a provided path
|
||||
Function Install-Program {
|
||||
param(
|
||||
[Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$Path,
|
||||
@@ -217,24 +217,24 @@ Function Install-Program {
|
||||
[Parameter(Mandatory=$false)][switch]$Delete = $false
|
||||
)
|
||||
If ( Test-Path "${Path}" ) {
|
||||
LogMsg "Running installer: ""${Path}"" ${Arguments}"
|
||||
Write-Output "Running installer: ""${Path}"" ${Arguments}"
|
||||
Try {
|
||||
If ( $Arguments -eq '' ) { Start-Process "${Path}" -Wait }
|
||||
Else { Start-Process "${Path}" -ArgumentList "${Arguments}" -Wait }
|
||||
}
|
||||
Catch { LogErr $_.Exception.Message }
|
||||
LogMsg "Installer finished"
|
||||
Catch { Write-Error $_.Exception.Message }
|
||||
Write-Output "Installer finished"
|
||||
If ( $Delete ) {
|
||||
LogMsg "Deleting installer: ""${Path}"""
|
||||
Write-Output "Deleting installer: ""${Path}"""
|
||||
Try { Remove-Item -Path "${Path}" -Force }
|
||||
Catch { LogErr $_.Exception.Message }
|
||||
Catch { Write-Error $_.Exception.Message }
|
||||
}
|
||||
}
|
||||
Else { LogMsg "The specified file could not be found: ""${Path}""" }
|
||||
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
|
||||
# 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,
|
||||
@@ -253,8 +253,8 @@ Function IsWindowsVersion {
|
||||
}
|
||||
}
|
||||
|
||||
## Compare current Windows build with a supplied version
|
||||
## The value supplied must be an int
|
||||
# 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,
|
||||
@@ -273,19 +273,19 @@ Function IsWindowsBuild {
|
||||
}
|
||||
}
|
||||
|
||||
## Get the path to the TEMP folder (context dependent)
|
||||
# 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
|
||||
# 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
|
||||
# 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
|
||||
# Determine if a user is in a built-in role or specified group
|
||||
Function IsMemberOf {
|
||||
param(
|
||||
[Parameter(Mandatory=$false)]
|
||||
@@ -319,7 +319,7 @@ Function IsMemberOf {
|
||||
Return ([Security.Principal.WindowsPrincipal][System.Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole($Group)
|
||||
}
|
||||
|
||||
## Start, stop, restart, or delete a list of services
|
||||
# Start, stop, restart, or delete a list of services
|
||||
Function Control-Service
|
||||
{
|
||||
param(
|
||||
@@ -366,7 +366,7 @@ Function Control-Service
|
||||
Exit
|
||||
}
|
||||
'delete' {
|
||||
## Delete the service
|
||||
# Delete the service
|
||||
}
|
||||
'disable' {
|
||||
$ArgString = $MyInvocation.Line
|
||||
@@ -381,9 +381,9 @@ Function Control-Service
|
||||
ForEach ( $item in $Name ) {
|
||||
$service = Get-Service -Name $item -ErrorAction SilentlyContinue
|
||||
If ( !($service) ) {
|
||||
LogMsg "Cannot find the service '${item}'"
|
||||
Write-Output "Cannot find the service '${item}'"
|
||||
If ( $Match ) {
|
||||
LogMsg "Attempting to match '${item}' to service display names"
|
||||
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 }
|
||||
@@ -403,7 +403,7 @@ Function Control-Service
|
||||
$displayname = """${fullname}"" (${name})"
|
||||
}
|
||||
If ( $service.Status -ne $statuscondition ) {
|
||||
LogMsg "${verbing} ${displayname}"
|
||||
Write-Output "${verbing} ${displayname}"
|
||||
Try {
|
||||
Switch ( $verb) {
|
||||
'start' { Start-Service -Name $name }
|
||||
@@ -411,13 +411,13 @@ Function Control-Service
|
||||
'disable' { Set-Service -Name "${name}" -StartupType Disabled }
|
||||
}
|
||||
}
|
||||
Catch { LogErr $_.Exception.Message }
|
||||
Catch { Write-Error $_.Exception.Message }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
## Stop a process
|
||||
# Stop a process
|
||||
Function End-Process
|
||||
{
|
||||
param(
|
||||
@@ -428,9 +428,9 @@ Function End-Process
|
||||
ForEach ( $item in $Name ) {
|
||||
$process = Get-Process -Name $item -ErrorAction SilentlyContinue
|
||||
If ( !($process) ) {
|
||||
LogMsg "Cannot find the process '${item}'"
|
||||
Write-Output "Cannot find the process '${item}'"
|
||||
If ( $Match ) {
|
||||
LogMsg "Attempting to match '${item}' to all running process names"
|
||||
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 }
|
||||
}
|
||||
@@ -439,11 +439,11 @@ Function End-Process
|
||||
Else {
|
||||
$name = $process.Name
|
||||
If ( $Force ) {
|
||||
LogMsg "Forcefully stopping '${name}' process"
|
||||
Write-Output "Forcefully stopping '${name}' process"
|
||||
Stop-Process $process -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
Else {
|
||||
LogMsg "Attempting to gracefully close '${name}' process"
|
||||
Write-Output "Attempting to gracefully close '${name}' process"
|
||||
$process.CloseMainWindow() | Out-Null
|
||||
}
|
||||
}
|
||||
@@ -461,9 +461,9 @@ Function Create-Shortcut {
|
||||
)
|
||||
If ( Test-Path $TargetPath ) {
|
||||
If ( Test-Path $Path ) {
|
||||
LogMsg "Deleting existing shortcut at ""${Path}"""
|
||||
Write-Output "Deleting existing shortcut at ""${Path}"""
|
||||
Try { Remove-Item $Path -Force -ErrorAction SilentlyContinue }
|
||||
Catch { LogErr $_.Exception.Message }
|
||||
Catch { Write-Error $_.Exception.Message }
|
||||
}
|
||||
If ( $WorkingDirectory -eq '' ) { $WorkingDirectory = Split-Path $TargetPath -Parent }
|
||||
If ( $Icon -eq '' ) { $Icon = "${TargetPath}, 0" }
|
||||
@@ -474,11 +474,11 @@ Function Create-Shortcut {
|
||||
$Shortcut.IconLocation = $Icon
|
||||
$Shortcut.WorkingDirectory = $WorkingDirectory
|
||||
$Shortcut.TargetPath = $TargetPath
|
||||
LogMsg "Creating shortcut to ""${TargetPath}"" at ""${Path}"""
|
||||
Write-Output "Creating shortcut to ""${TargetPath}"" at ""${Path}"""
|
||||
Try { $Shortcut.Save() }
|
||||
Catch { LogErr $_.Exception.Message }
|
||||
Catch { Write-Error $_.Exception.Message }
|
||||
}
|
||||
Else { LogMsg "Cannot create shortcut because the target path does not exist" }
|
||||
Else { Write-Output "Cannot create shortcut because the target path does not exist" }
|
||||
}
|
||||
|
||||
# Function to enable or disable a specified log
|
||||
@@ -490,11 +490,11 @@ Function Toggle-Log {
|
||||
)
|
||||
Try {
|
||||
$log = New-Object System.Diagnostics.Eventing.Reader.EventLogConfiguration $Name
|
||||
If ( $Enable ) { LogMsg "Enabing ${Name} event log" ; $log.IsEnabled = $true }
|
||||
If ( $Disable ) { LogMsg "Disabing ${Name} event log" ; $log.IsEnabled = $false }
|
||||
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 { LogMsg $_.Exception.Message }
|
||||
Catch { Write-Output $_.Exception.Message }
|
||||
}
|
||||
|
||||
# Function to install the PSAtera Powershell module
|
||||
@@ -502,14 +502,14 @@ Function Install-PSAteraModule {
|
||||
Try {
|
||||
$module = Get-Module -ListAvailable -Name PSAtera
|
||||
If ( (-not $module) -and (IsAdmin) ) {
|
||||
LogMsg "Installing PSAtera Powershell module"
|
||||
Write-Output "Installing PSAtera Powershell module"
|
||||
Install-Module -Name PSAtera -Force
|
||||
}
|
||||
ElseIf ( (-not $module) -and (-not (IsAdmin)) ) {
|
||||
LogMsg "The PSAtera module needs to be installed, but the current security context is not sufficient to install it"
|
||||
Write-Output "The PSAtera module needs to be installed, but the current security context is not sufficient to install it"
|
||||
}
|
||||
}
|
||||
Catch { LogErr $_.Exception.Message }
|
||||
Catch { Write-Error $_.Exception.Message }
|
||||
}
|
||||
|
||||
# Function to install the MSP360 Powershell module
|
||||
@@ -517,15 +517,15 @@ Function Install-MSP360Module {
|
||||
Try {
|
||||
$module = Get-Module -ListAvailable -Name MSP360
|
||||
If ( (-not $module) -and (IsAdmin) ) {
|
||||
LogMsg "Installing MSP360 Powershell module"
|
||||
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)) ) {
|
||||
LogMsg "The MSP360 Powershell module needs to be installed, but the current security context is not sufficient to install it"
|
||||
Write-Output "The MSP360 Powershell module needs to be installed, but the current security context is not sufficient to install it"
|
||||
}
|
||||
}
|
||||
Catch { LogErr $_.Exception.Message }
|
||||
Catch { Write-Error $_.Exception.Message }
|
||||
}
|
||||
|
||||
# Function to delete a file
|
||||
@@ -533,10 +533,10 @@ Function Remove-File ([Parameter(ValueFromPipeline=$true)][string]$path) {
|
||||
If ( Test-Path $path ) {
|
||||
If ( !((Get-Item $path) -is [System.IO.DirectoryInfo]) ) {
|
||||
Try {
|
||||
LogMsg "Delete ""${path}"""
|
||||
Write-Output "Delete ""${path}"""
|
||||
Remove-Item $path -Force
|
||||
}
|
||||
Catch { LogErr $_.Exception.Message }
|
||||
Catch { Write-Error $_.Exception.Message }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -549,40 +549,40 @@ Function Zip-Object {
|
||||
)
|
||||
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) }
|
||||
LogMsg "Creating zip file of: ${path}"
|
||||
Write-Output "Creating zip file of: ${path}"
|
||||
Try {
|
||||
Add-Type -Assembly "System.IO.Compression.FileSystem"
|
||||
[IO.Compression.ZipFile]::CreateFromDirectory($path, $dest)
|
||||
}
|
||||
Catch { LogErr $_.Exception.Message }
|
||||
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 {
|
||||
LogMsg "Creating directory: ${path}"
|
||||
Write-Output "Creating directory: ${path}"
|
||||
New-Item -ItemType Directory -Path $dir -ErrorAction Stop | Out-Null
|
||||
LogMsg "Moving ""${path}"" into ""${dir}"""
|
||||
Write-Output "Moving ""${path}"" into ""${dir}"""
|
||||
Move-Item -Path $path -Destination $dir -Force -ErrorAction Stop | Out-Null
|
||||
}
|
||||
Catch { LogErr $_.Exception.Message }
|
||||
Catch { Write-Error $_.Exception.Message }
|
||||
Zip-Object $dir
|
||||
}
|
||||
Else { LogMsg "Could not determine the file/folder status: ${path}" }
|
||||
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
|
||||
LogMsg "Extracting ""${path}"" to ""${dest}"""
|
||||
Write-Output "Extracting ""${path}"" to ""${dest}"""
|
||||
Try {
|
||||
Add-Type -Assembly "System.IO.Compression.FileSystem"
|
||||
[IO.Compression.ZipFile]::ExtractToDirectory($path, $dest)
|
||||
}
|
||||
Catch { LogErr $_.Exception.Message }
|
||||
Catch { Write-Error $_.Exception.Message }
|
||||
}
|
||||
Else { LogMsg "The path specified is not a zip file: ${path}" }
|
||||
Else { Write-Output "The path specified is not a zip file: ${path}" }
|
||||
}
|
||||
|
||||
# Function to get a copy of the LiquidFiles CLI agent
|
||||
@@ -592,14 +592,14 @@ Function Get-LiquidFilesCLI {
|
||||
$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 ) {
|
||||
LogMsg "Deleting existing zip archive: ${zip_path}"
|
||||
Write-Output "Deleting existing zip archive: ${zip_path}"
|
||||
Try { Remove-Item -Path $zip_path -Force }
|
||||
Catch { LogErr $_.Exception.Message }
|
||||
Catch { Write-Error $_.Exception.Message }
|
||||
}
|
||||
If ( Test-Path $exe_path ) {
|
||||
LogMsg "Deleting existing file: ${exe_path}"
|
||||
Write-Output "Deleting existing file: ${exe_path}"
|
||||
Try { Remove-Item -Path $exe_path -Force }
|
||||
Catch { LogErr $_.Exception.Message }
|
||||
Catch { Write-Error $_.Exception.Message }
|
||||
}
|
||||
Download-File -URL $url -File $zip_path | Out-Null
|
||||
Unzip-Object $zip_path
|
||||
@@ -623,35 +623,35 @@ Function Create-LocalUser {
|
||||
[Parameter(Mandatory=$false)][switch]$Hide=$false
|
||||
)
|
||||
|
||||
## Secure supplied password
|
||||
# Secure supplied password
|
||||
Try { $SecurePassword = ConvertTo-SecureString $Password -AsPlainText -Force ; $Password = $null }
|
||||
Catch { LogErr $_.Exception.Message ; Exit }
|
||||
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) )
|
||||
{
|
||||
LogMsg "Updating user: ${Username}"
|
||||
Write-Output "Updating user: ${Username}"
|
||||
Try { Set-LocalUser -Name $Username -Password $SecurePassword -FullName $FullName -Description $Description -AccountNeverExpires -PasswordNeverExpires }
|
||||
Catch { LogErr $_.Exception.Message ; Exit }
|
||||
Catch { Write-Error $_.Exception.Message ; Exit }
|
||||
}
|
||||
Else
|
||||
{
|
||||
LogMsg "Creating user: ${Username}"
|
||||
Write-Output "Creating user: ${Username}"
|
||||
Try { New-LocalUser -Name $Username -Password $SecurePassword -FullName $FullName -Description $Description -AccountNeverExpires -PasswordNeverExpires }
|
||||
Catch { LogErr $_.Exception.Message ; Exit }
|
||||
Catch { Write-Error $_.Exception.Message ; Exit }
|
||||
}
|
||||
If ( (-not($(Get-LocalGroupMember -Group "Administrators" -Member $Username -ErrorAction SilentlyContinue))) -and $MakeAdmin )
|
||||
{
|
||||
LogMsg "Adding ""${Username}"" to local Administrators group"
|
||||
Write-Output "Adding ""${Username}"" to local Administrators group"
|
||||
Try { Add-LocalGroupMember -Name "Administrators" -Member $(Get-LocalUser -Name $Username) }
|
||||
Catch { LogErr $_.Exception.Message ; Exit }
|
||||
Catch { Write-Error $_.Exception.Message ; Exit }
|
||||
}
|
||||
}
|
||||
Else { LogMsg "Cannot create or modify local accounts on a domain controller" }
|
||||
Else { Write-Output "Cannot create or modify local accounts on a domain controller" }
|
||||
}
|
||||
Else { LogMsg "Cannot create or modify a local account without administrative privileges" }
|
||||
Else { Write-Output "Cannot create or modify a local account without administrative privileges" }
|
||||
|
||||
If ( $Hide ) {
|
||||
# TODO: Hide account from logon screen
|
||||
@@ -669,9 +669,9 @@ Function Stop-MemoryHog ([string]$AppName,[int]$MemoryLimit) {
|
||||
$MemoryUsed = (Get-MemoryUsage -AppName $AppName)
|
||||
If ( $MemoryUsed -gt $MemoryLimit ) {
|
||||
$MemoryDifference = $MemoryUsed - $MemoryLimit
|
||||
LogMsg "Killing ""${AppName}"" for using ${MemoryDifference}MB over the limit of ${MemoryLimit}MB"
|
||||
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 { LogErr $_.Exception.Message }
|
||||
Catch { Write-Error $_.Exception.Message }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -723,7 +723,7 @@ Function Get-FileSizes {
|
||||
|
||||
# Output to log file
|
||||
$logstr = "${prefix}" + $($FileSizes | Format-List | Out-String)
|
||||
LogMsg $logstr
|
||||
Write-Output $logstr
|
||||
}
|
||||
|
||||
# Function to write text to a file in UTF8 encoding without BOM
|
||||
@@ -734,7 +734,7 @@ Function WriteToFile_UTF8NoBOM {
|
||||
)
|
||||
$UTF8NoBOM = New-Object System.Text.UTF8Encoding $false
|
||||
Try { [IO.File]::WriteAllText($FilePath, $CONFIG, $UTF8NoBOM) }
|
||||
Catch { LogErr $_.Exception.Message }
|
||||
Catch { Write-Error $_.Exception.Message }
|
||||
}
|
||||
|
||||
# Function to enumerate all user profile folders
|
||||
@@ -813,7 +813,7 @@ Function Uninstall-MSI ([Parameter(ValueFromPipeline=$true)][string[]]$APP_NAMES
|
||||
$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 ) { LogErr "Attempted to uninstall ${APP_NAMES} but could not find any installed apps in the Windows Registry" ; Return }
|
||||
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 = @()
|
||||
@@ -862,15 +862,15 @@ Function Uninstall-MSI ([Parameter(ValueFromPipeline=$true)][string[]]$APP_NAMES
|
||||
|
||||
# Print out uninstall string for unsupported apps
|
||||
If ( $installed_app.UninstallSupported -eq $false ) {
|
||||
LogMsg "Cannot uninstall ""${DisplayName}""`n UninstallString: ${UninstallString}"
|
||||
Write-Output "Cannot uninstall ""${DisplayName}""`n UninstallString: ${UninstallString}"
|
||||
Continue
|
||||
}
|
||||
|
||||
# Uninstall the app
|
||||
LogMsg "Uninstalling ""${DisplayName}"" with product code: ${ProductCode}"
|
||||
Write-Output "Uninstalling ""${DisplayName}"" with product code: ${ProductCode}"
|
||||
$arguments = '/X{' + $ProductCode + '} /qn /norestart'
|
||||
Try { Start-Process -FilePath "msiexec.exe" -ArgumentList $arguments -Wait }
|
||||
Catch { LogErr $_.Exception.Message }
|
||||
Catch { Write-Error $_.Exception.Message }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -881,7 +881,7 @@ 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 { LogErr $_.Exception.Message ; Exit }
|
||||
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)
|
||||
@@ -891,7 +891,7 @@ Function Restart-EndpointOnUptime ([timespan]$MaxUptime) {
|
||||
|
||||
# Reboot the endpoint
|
||||
Try { Restart-Computer -Force -ErrorAction Stop }
|
||||
Catch { LogErr $_.Exception.Message }
|
||||
Catch { Write-Error $_.Exception.Message }
|
||||
}
|
||||
|
||||
Setup-MSPDirectories
|
||||
|
||||
Reference in New Issue
Block a user