major logging overhaul, plus other fixes

This commit is contained in:
2020-10-22 14:01:35 -04:00
parent 77cf4d6276
commit 978373ebe2
27 changed files with 430 additions and 611 deletions
+124 -49
View File
@@ -12,13 +12,14 @@ $MSPLogs = "${MSPRoot}\Logs"
$MSPRoot, $MSPScripts, $MSPTools, $MSPLogs | ForEach-Object {
If ( !(Test-Path $_) )
{
Try { New-Item -Path $MSPRoot -ItemType Directory -Force -ErrorAction SilentlyContinue | Out-Null }
Catch { Write-Output $_.Exception.Message ; Exit }
Try { New-Item -Path $_ -ItemType Directory -Force -ErrorAction SilentlyContinue | Out-Null }
Catch { Write-Output $_.Exception.Message }
}
}
## Set a file prefix for any logs that might need to be created
$LogFilePrefix = Get-Date -Format "yyyyMMddHHmmss"
## Setup the log file for messages generated when this script is run
$LogFile = '{0}\ManagementScript_{1}.log' -f $MSPLogs, (Get-Date -Format "yyyyMMddHHmmss")
If ( !(Test-Path $LogFile) ) { New-Item -Path $LogFile -ItemType File -Force | Out-Null }
## Function to log activity to the configured log directory
Function Log
@@ -31,14 +32,28 @@ param(
$Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
If ( $Error ) { $LogEntry = "${Timestamp} - Error: ${Message}" }
Else { $LogEntry = "${Timestamp} - ${Message}" }
If ( $Name )
{
$LogFile = "${MSPLogs}\${LogFilePrefix}-${Name}.log"
If ( !(Test-Path $LogFile) ) { New-Item -Path $LogFile -ItemType File -Force | Out-Null }
Add-Content -Path $LogFile -Value $LogEntry
Write-Output $LogEntry
Add-Content -Path $LogFile -Value $LogEntry
Write-Output $LogEntry
}
Else { Write-Output $LogEntry }
## Log a message to the log file
Function LogMsg
{
param([Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$Message)
$Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$LogEntry = "${Timestamp} - ${Message}"
Add-Content -Path $LogFile -Value $LogEntry
#Write-Output $LogEntry
}
## Log an error to the log file
Function LogErr
{
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 $LogFile -Value $LogEntry
#Write-Output "Error: ${LogEntry}"
}
## Function to determine if the current user context is an Administrator
@@ -76,20 +91,19 @@ param(
[Parameter(Mandatory=$false,ParameterSetName='local')]
[switch]$ForceClose=$false
)
$LogName = $MyInvocation.MyCommand
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) ) { Log "The specified script does not exist: ${LivePSScript}" -Name $LogName ; Exit }
If ( !(IsURLValid -URL $URL) ) { LogMsg "The specified script does not exist: ${LivePSScript}" ; Exit }
}
If ( $Path ) { If ( !(Test-Path $Path) ) { Log "The specified script does not exist: ${Path}" -Name $LogName ; Exit } }
If ( ($HaltIfRunning -ne $null ) -and ($ForceClose) -and ( !(IsAdmin) ) ) { Log "Cannot close dependent apps because this task does not have administrative privileges" -Name $LogName ; Exit }
If ( $Path ) { If ( !(Test-Path $Path) ) { LogMsg "The specified script does not exist: ""${Path}""" ; Exit } }
If ( ($HaltIfRunning -ne $null ) -and ($ForceClose) -and ( !(IsAdmin) ) ) { LogMsg "Cannot close dependent apps because this task does not have administrative privileges" ; Exit }
If ( $HaltIfRunning )
{
$Halt = $false
Log "Checking for running instances of the following dependent apps:" -Name $LogName
LogMsg "Checking for running instances of the following dependent apps:"
ForEach ( $name in $HaltIfRunning)
{
$RunningInstances = Get-Process | Where { $_.Name -like "${name}" }
@@ -98,48 +112,49 @@ If ( $HaltIfRunning )
If ( $ForceClose -eq $true )
{
Try { $name | Stop-Process -Force }
Catch { $_.Exception.Message | Log -Name $LogName ; Exit }
Catch { LogErr $_.Exception.Message ; Exit }
Log " ""${name}"" (force closed)" -Name $LogName
}
Else { $Halt = $true ; Log " ""${name}"" (running)" -Name $LogName }
Else { $Halt = $true ; LogMsg " ""${name}"" (running)" }
}
Else { Log " ""${name}"" (not running)" -Name $LogName }
Else { LogMsg " ""${name}"" (not running)" }
}
If ( $Halt -eq $true ) { Log "Dependent apps are currently in use and are preventing the specified script from running" -Name $LogName ; Exit }
If ( $Halt -eq $true ) { LogMsg "Dependent apps are currently in use and are preventing the specified script from running" ; Exit }
}
switch ($PSCmdlet.ParameterSetName)
{
'live-ps'
{
Log "Retrieving : ${LivePSScript}.ps1" -Name $LogName
LogMsg "Retrieving : ${LivePSScript}.ps1"
Try { $Script = (New-Object Net.WebClient).DownloadString($URL) }
Catch { $_.Exception.Message | Log -Name $LogName ; Exit }
Catch { LogErr $_.Exception.Message ; Exit }
Try { $ScriptBlock = [Scriptblock]::Create($Script) }
Catch { $_.Exception.Message | Log -Name $LogName ; Exit }
Log "Executing: ${LivePSScript}.ps1 ${Arguments}"
Catch { LogErr $_.Exception.Message ; Exit }
LogMsg "Executing: ${LivePSScript}.ps1 ${Arguments}"
Try { Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arguments }
Catch { $_.Exception.Message | Log -Name $LogName ; Exit }
Catch { LogErr $_.Exception.Message ; Exit }
}
'local'
{
Log "Executing: ${Path} ${Arguments}" -Name $LogName
Try
LogMsg "Executing: ${Path} ${Arguments}"
If ( $NoWait )
{
If ( $NoWait ) { Start-Process "${Path}" -ArgumentList "{$Arguments}" }
Else
{
Log " Waiting for script to finish..." -Name $LogName
Start-Process "${Path}" -ArgumentList "{$Arguments}" -Wait
Log " Finished" -Name $LogName
}
Try { Start-Process "${Path}" -ArgumentList "{$Arguments}" }
Catch { LogErr $_.Exception.Message }
}
Else
{
LogMsg " Waiting for script to finish..."
Try { Start-Process "${Path}" -ArgumentList "{$Arguments}" -Wait }
Catch { LogErr $_.Exception.Message }
LogMsg " Finished"
}
Catch { $_.Exception.Message | Log -Name $LogName ; Exit }
}
}
}
## Function to 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)
@@ -167,30 +182,53 @@ If ($HTTPStatus -eq 200) { 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
)
$LogName = $MyInvocation.MyCommand
If ( !($File) ) { $File = '{0}\{1}' -f $Env:TEMP, (Split-Path $URL -Leaf) }
If ( !($File) ) { $File = '{0}{1}' -f (GetTempPath), (Split-Path $URL -Leaf) }
If ( IsURLValid $URL )
{
If ( Test-Path $File )
{
Log "Deleting existing file: ""${File}""" -Name $LogName
LogMsg "Deleting existing file: ""${File}"""
Try { Remove-Item $File -Force }
Catch { $_.Exception.Message | Log -Name $LogName }
Catch { LogErr $_.Exception.Message }
}
Log "Downloading ""${URL}"" to ""${File}""" -Name $LogName
LogMsg "Downloading ""${URL}"" to ""${File}"""
Try { (New-Object System.Net.WebClient).DownloadFile($URL,$File) }
Catch { $_.Exception.Message | Log -Name $LogName }
If ( Test-Path $File )
{ Return $File }
Else { Log "The file was downloaded but was immediately deleted" -Name $LogFile ; Return $false }
Catch { LogErr $_.Exception.Message }
If ( Test-Path "${File}" ) { Return "${File}" }
Else { LogMsg "Downloaded file does not exist at ""${File}""" ; Return $false }
}
Else { Log "URL is not valid or file cannot be reached: ${URL}" -Name $LogName }
Else { LogMsg "URL is not valid or file cannot be reached: ${URL}" }
}
## Install a program from a provided path
Function Install-Program
{
param(
[Parameter(Mandatory=$true)][string]$Path,
[Parameter(Mandatory=$false)][string]$Arguments = '',
[Parameter(Mandatory=$false)][switch]$Delete = $false
)
If ( Test-Path "${Path}" )
{
LogMsg "Running installer: ""${Path}"" ${Arguments}"
Try { Start-Process "${Path}" -ArgumentList "${Arguments}" -Wait }
Catch { LogErr $_.Exception.Message }
LogMsg "Installer finished"
If ( $Delete )
{
LogMsg "Deleting installer: ""${Path}"""
Try { Remove-Item -Path "${Path}" -Force }
Catch { LogErr $_.Exception.Message }
}
}
Else { LogMsg "The specified file could not be found: ""${Path}""" }
}
## Function to compare current Windows version with a supplied version
@@ -215,7 +253,7 @@ switch ($PSCmdlet.ParameterSetName)
}
}
## Function to compare current Windows build with a supplied version
## Compare current Windows build with a supplied version
## The value supplied must be an int
Function IsWindowsBuild
{
@@ -237,14 +275,51 @@ switch ($PSCmdlet.ParameterSetName)
}
}
## Function to determine if the system is 64-bit or not
## Get the path to the TEMP folder (context dependant)
Function GetTempPath
{ 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 } }
}
## Function to 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
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)
}