diff --git a/Cleanup-SystemPath.ps1 b/Cleanup-SystemPath.ps1 index e83303f..7eb2c9d 100644 --- a/Cleanup-SystemPath.ps1 +++ b/Cleanup-SystemPath.ps1 @@ -1,8 +1,4 @@ -## Source the tools script if it isn't already available -If ( !($MSPName) ) { . $([Scriptblock]::Create((New-Object Net.WebClient).DownloadString('https://dev.emberkom.com/emberkom/management-scripts/raw/branch/master/Tools.ps1'))) } - -## Set the name of the log file -$LogName = 'Cleanup-SystemPath' +LogMsg "Cleanup-SystemPath.ps1" ## Get contents of SYSTEM PATH environment variable $REG_ENVVAR = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' @@ -25,18 +21,18 @@ Foreach ( $path in $CURRENT_PATH.Split(";") ) } } -Log "Removed Paths:`n`r${REMOVE_PATH}" -Name $LogName +LogMsg "Removed Paths:`n`r${REMOVE_PATH}" Try { Set-ItemProperty -Path $REG_ENVVAR -Name Path -Value $NEW_PATH } Catch { $_.Exception.Message | Log -Error -Name $LogName - Log "Failed to cleanup system path, using original values" -Error -Name $LogName + LogErr "Failed to cleanup system path, using original values" Try { Set-ItemProperty -Path $REG_ENVVAR -Name Path -Value $CURRENT_PATH } Catch { - $_.Exception.Message | Log -Error -Name $LogName - Log "This is not good... !! DO NOT RESTART UNTIL SYSTEM PATH IS FIXED !!" -Error -Name $LogName + LogErr $_.Exception.Message + LogErr "This is not good... !! DO NOT RESTART UNTIL SYSTEM PATH IS FIXED !!" Exit } } \ No newline at end of file diff --git a/Cleanup-SystemTempFiles.ps1 b/Cleanup-SystemTempFiles.ps1 index cb0ffa3..8f316bb 100644 --- a/Cleanup-SystemTempFiles.ps1 +++ b/Cleanup-SystemTempFiles.ps1 @@ -1,8 +1,4 @@ -## Source the tools script if it isn't already available -If ( !($MSPName) ) { . $([Scriptblock]::Create((New-Object Net.WebClient).DownloadString('https://dev.emberkom.com/emberkom/management-scripts/raw/branch/master/Tools.ps1'))) } - -## Set the name of the log file -$LogName = 'Cleanup-SystemTempFiles' +LogMsg "Cleanup-SystemTempFiles.ps1" ## Path to the system temp folder $SysTemp = "${Env:SystemRoot}\TEMP" @@ -14,13 +10,13 @@ $TimeDelta = New-TimeSpan -Days $OlderThan ## Only run this section if we have administrative privileges If ( IsAdmin ) { - Log "Running with administrative privileges" -Name $LogName + LogMsg "Running with administrative privileges" ## Remove all *.evtx files from $SysTemp $EventLogs = Get-ChildItem -Path "${SysTemp}\*" -File -Filter *.evtx If ( $EventLogs ) { - Log "Deleting all event logs from ${SysTemp}" -Name $LogName + LogMsg "Deleting all event logs from ${SysTemp}" ForEach ( $EventLog in $EventLogs ) { Remove-Item $EventLog -Force -ErrorAction SilentlyContinue } } @@ -28,7 +24,7 @@ If ( IsAdmin ) $MiscLogs = Get-ChildItem -Path "${SysTemp}\*" -File -Include "${Env:COMPUTERNAME}-*.log", "AppxErrorReport_*.txt" If ( $MiscLogs ) { - Log "Deleting misc logs from ${SysTemp}" -Name $LogName + LogMsg "Deleting misc logs from ${SysTemp}" ForEach ( $MiscLog in $MiscLogs ) { Remove-Item $MiscLog -Force -ErrorAction SilentlyContinue } } @@ -36,7 +32,7 @@ If ( IsAdmin ) $CBSLogs = Get-ChildItem -Path "${Env:SystemRoot}\Logs\CBS\*" -File -Include "CbsPersist_*.log", "CbsPersist_*.cab" If ( $CBSLogs ) { - Log "Deleting archived CBS logs from ${Env:SystemRoot}\Logs\CBS" -Name $LogName + LogMsg "Deleting archived CBS logs from ${Env:SystemRoot}\Logs\CBS" ForEach ( $CBSLog in $CBSLogs ) { Remove-Item $CBSLog -Force -ErrorAction SilentlyContinue } } @@ -45,29 +41,29 @@ If ( IsAdmin ) $OldTempFiles = Get-ChildItem -Path $SysTemp | Where { $_.LastWriteTime -lt ((Get-Date) - $TimeDelta) } If ( $OldTempFiles ) { - Log "Deleting all temp files not modified in ${OlderThan} day(s) from ${SysTemp}" -Name $LogName + LogMsg "Deleting all temp files not modified in ${OlderThan} day(s) from ${SysTemp}" ForEach ( $OldTempFile in $OldTempFiles ) { Remove-Item $OldTempFile -Force -Recurse -ErrorAction SilentlyContinue } } ## Turn off system hibernation if it's in use If ( Test-Path "${Env:SystemDrive}\hiberfil.sys" ) { - Log "Turning off system hibernation" -Name $LogName + LogMsg "Turning off system hibernation" Try { Start-Process "powercfg" -ArgumentList "-h off" -Wait } - Catch { $_.Exception.Message | Log -Error -Name $LogName } + Catch { LogErr $_.Exception.Message } } } ## Only run this section if we don't have administrative privileges Else { - Log "Running without administrative privileges" + LogMsg "Running without administrative privileges" ## Remove all system temp files older than 7 days $OldTempFiles = Get-ChildItem -Path $Env:TEMP | Where { $_.LastWriteTime -lt ((Get-Date) - $TimeDelta) } If ( $OldTempFiles ) { - Log "Deleting all temp files not modified in ${OlderThan} day(s) from ${Env:TEMP}" -Name $LogName + LogMsg "Deleting all temp files not modified in ${OlderThan} day(s) from ${Env:TEMP}" ForEach ( $OldTempFile in $OldTempFiles ) { Remove-Item $OldTempFile -Force -Recurse -ErrorAction SilentlyContinue } } } diff --git a/Create-LocalAdmin.ps1 b/Create-LocalAdmin.ps1 index e889057..2df1910 100644 --- a/Create-LocalAdmin.ps1 +++ b/Create-LocalAdmin.ps1 @@ -1,46 +1,41 @@ -## Source the tools script if it isn't already available -If ( !($MSPName) ) { . $([Scriptblock]::Create((New-Object Net.WebClient).DownloadString('https://dev.emberkom.com/emberkom/management-scripts/raw/branch/master/Tools.ps1'))) } - #Requires -Version 5.1 -Function Create-LocalAdmin -{ + param( [Parameter(Mandatory=$true)][string]$Username, [Parameter(Mandatory=$true)][string]$Password, [Parameter(Mandatory=$true)][string]$FullName, [Parameter(Mandatory=$true)][string]$Description ) -$LogName = $MyInvocation.MyCommand -Log "Securing supplied password" -Name $LogName +LogMsg "Create-LocalAdmin.ps1" +LogMsg "Securing supplied password" Try { $SecurePassword = ConvertTo-SecureString $Password -AsPlainText -Force ; $Password = $null } -Catch { $_.Exception.Message | Log -Error -Name $LogName ; Exit } +Catch { LogErr $_.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) ) { - Log "Updating user: ${Username}" -Name $LogName + LogMsg "Updating user: ${Username}" Try { Set-LocalUser -Name $Username -Password $SecurePassword -FullName $FullName -Description $Description -AccountNeverExpires -PasswordNeverExpires $true } - Catch { $_.Exception.Message | Log -Error -Name $LogName ; Exit } + Catch { LogErr $_.Exception.Message ; Exit } } Else { - Log "Creating user: ${Username}" -Name $LogName + LogMsg "Creating user: ${Username}" Try { New-LocalUser -Name $Username -Password $SecurePassword -FullName $FullName -Description $Description -AccountNeverExpires -PasswordNeverExpires $true } - Catch { $_.Exception.Message | Log -Error -Name $LogName ; Exit } + Catch { LogErr $_.Exception.Message ; Exit } } If ( !($(Get-LocalGroupMember -Group "Administrators" -Member $Username -ErrorAction SilentlyContinue)) ) { - Log "Adding ""${Username}"" to local Administrators group" -Name $LogName + LogMsg "Adding ""${Username}"" to local Administrators group" Try { Add-LocalGroupMember -Group "Administrators" -Member $Username } - Catch { $_.Exception.Message | Log -Error -Name $LogName ; Exit } + Catch { LogErr $_.Exception.Message ; Exit } } } - Else { Log "The local user account ""${Username}"" cannot be created on a domain controller" -Name $LogName } + Else { LogMsg "The local user account ""${Username}"" cannot be created on a domain controller" } } -Else { Log "Cannot create a local administrator account without administrative privileges" -Name $LogName } +Else { LogMsg "Cannot create a local administrator account without administrative privileges" } ## TODO: Hide account from logon screen #Get-ChildItem "HKLM:SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts\UserList" -} \ No newline at end of file diff --git a/Download-Tools.ps1 b/Download-Tools.ps1 deleted file mode 100644 index ed1cbc6..0000000 --- a/Download-Tools.ps1 +++ /dev/null @@ -1,61 +0,0 @@ -## Define the tools and URLs to them -$URLS = @( - 'https://emberkom.s3.amazonaws.com/tools/LiquidFilesCLI.exe', - 'https://emberkom.s3.amazonaws.com/tools/7za.exe' - ) - -## Test for write access to tools directory, redirect to AppData If denied -$TOOLS = "${Env:ProgramData}\Emberkom\Tools" -$TEST_FILE = "${TOOLS}\testfile.txt" - -## Test to see if $TOOLS exists -If (!( Test-Path $TOOLS )) -{ - ## If $TOOLS does not exist, create it. - Try { New-Item -ItemType Directory -Path $TOOLS } - - ## If we get an error, switch to the logged on user's AppData directory - Catch - { - $TOOLS = "${Env:AppData}\Emberkom\Tools" - If ( !(Test-Path $TOOLS) ) { New-Item -ItemType Directory -Path $TOOLS } - } -} - -## If $TOOLS already exists... -Else -{ - ## Try to create a file to make sure we have permission to modify the files in there - Try - { - [IO.File]::OpenWrite($TEST_FILE).Close() - If ( Test-Path $TEST_FILE ) { Remove-Item $TEST_FILE -Force } - } - - ## If we get an error, switch to the logged on user's AppData directory - Catch - { - $TOOLS = "${Env:AppData}\Emberkom\Tools" - If ( !(Test-Path $TOOLS) ) { New-Item -ItemType Directory -Path $TOOLS } - } -} - -## Loop through each URL -ForEach ($url in $URLS) { - ## Set the tool name based on the URL path - $TOOL = $($url.Split('/') | Select-Object -Last 1) - - ## Delete any previous version of the tool - If ( Test-Path "${TOOLS}\${TOOL}" ) - { - Try { Remove-Item -Path "${TOOLS}\${TOOL}" } - Catch { Write-Host "Could not delete ${TOOLS}\${TOOL}"; exit } - } - - ## Download latest version of tool - If ( !( Test-Path "${TOOLS}\${TOOL}" )) - { - Try { (New-Object System.Net.WebClient).DownloadFile($url,"${TOOLS}\${TOOL}") } - Catch { Write-Host "Failed to download ${url}" } - } -} \ No newline at end of file diff --git a/Enable-SafeModeUtilities.bat b/Enable-SafeModeUtilities.bat deleted file mode 100644 index f7076db..0000000 --- a/Enable-SafeModeUtilities.bat +++ /dev/null @@ -1,4 +0,0 @@ -@echo off - -REM Enable NinjaRMM -reg add "HKLM\SYSTEM\CurrentControlSet\Control\SafeBoot\Network\NinjaRMMAgent" /ve /t Reg_SZ /f /d "Service" \ No newline at end of file diff --git a/Fix-WindowsHealth.ps1 b/Fix-WindowsHealth.ps1 index 7ac9f44..1ff3633 100644 --- a/Fix-WindowsHealth.ps1 +++ b/Fix-WindowsHealth.ps1 @@ -1,29 +1,28 @@ ## Run enhanced DISM for Windows 8 and higher endpoints If ( IsWindowsVersion -ge "6.2" ) { - ## The name of the log file for this script - $LogName = "Fix-WindowsHealth" + LogMsg "Fix-WindowsHealth.ps1" $BeginDISMRun = $(Get-Date).AddSeconds(-1) ## Scan the Windows Component Store for problems - Log "Beginning Windows Component Store scan" $LogName + LogMsg "Beginning Windows Component Store scan" Start-Process "dism.exe" -ArgumentList "/online /cleanup-image /scanhealth" -Wait - Log "Completed Windows Component Store scan" $LogName + LogMsg "Completed Windows Component Store scan" ## Check to see if the previous command recorded any problems that need repairing - Log "Beginning Windows Component Store health check" $LogName + LogMsg "Beginning Windows Component Store health check" $CheckHealthOutput = $(dism /online /cleanup-image /checkhealth) | Out-String If ( $CheckHealthOutput -match "repairable" ) { - Log "Completed Windows Component Store health check: Problems found" $LogName + LogMsg "Completed Windows Component Store health check: Problems found" ## Repair problems with the Windows Component Store - Log "Beginning Windows Component Store restoration" $LogName + LogMsg "Beginning Windows Component Store restoration" Start-Process "dism.exe" -ArgumentList "/online /cleanup-image /restorehealth" -Wait - Log "Completed Windows Component Store restoration" $LogName + LogMsg "Completed Windows Component Store restoration" } - Else { Log "Completed Windows Component Store health check: No problems found" $LogName } + Else { LogMsg "Completed Windows Component Store health check: No problems found" } $EndDISMRun = $(Get-Date).AddSeconds(1) @@ -31,12 +30,12 @@ If ( IsWindowsVersion -ge "6.2" ) $DISMLogFile = "${MSPLogs}\Fix-WindowsHealth_DISM.log" If ( Test-Path $DISMLogFile ) { Remove-Item $DISMLogFile -Force } New-Item -Path $DISMLogFile -ItemType File - Log "Beginning Windows Component Store log data collection" $LogName + LogMsg "Beginning Windows Component Store log data collection" Get-Content -Path "${Env:WinDir}\Logs\DISM\dism.log" | Select-String -Pattern '^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})' | % { If ( ((Get-Date $_.Line.Substring(0,19)) -gt $BeginDISMRun) -and ((Get-Date $_.Line.Substring(0,19)) -le $EndDISMRun) ) { Add-Content -Path $DISMLogFile -Value $_.Line } } - Log "Completed Windows Component Store log data collection" $LogName + LogMsg "Completed Windows Component Store log data collection" } -Else { Log "Online image cleanup and restoration is only supported on Windows 8 and higher" $LogName } \ No newline at end of file +Else { LogMsg "Online image cleanup and restoration is only supported on Windows 8 and higher" } \ No newline at end of file diff --git a/Fix-WindowsScriptingComponents.ps1 b/Fix-WindowsScriptingComponents.ps1 index bc46c67..1e73fe7 100644 --- a/Fix-WindowsScriptingComponents.ps1 +++ b/Fix-WindowsScriptingComponents.ps1 @@ -1,4 +1,6 @@ -## List of all scripting component DLL files +LogMsg "Fix-WindowsScriptingComponents.ps1" + +## List of all scripting component DLL files $DLL_FILES = @("${Env:WINDIR}\system32\vbscript.dll", "${Env:WINDIR}\system32\jscript.dll", "${Env:WINDIR}\system32\dispex.dll", @@ -20,7 +22,9 @@ ForEach ($dll in $DLL_FILES) If ( Test-Path $dll ) { If ( $dll -Match "syswow64" ) { $REGSVR32 = "${Env:WINDIR}\syswow64\regsvr32" } Else { $REGSVR32 = "regsvr32" } - Start-Process "${REGSVR32}" -ArgumentList "/u /s ${dll}" -Wait + LogMsg "Unregister: ${dll}" + Try { Start-Process "${REGSVR32}" -ArgumentList "/u /s ${dll}" -Wait } + Catch { LogErr $_.Exception.Message } } } @@ -31,6 +35,8 @@ ForEach ($dll in $DLL_FILES) { If ( $dll -Match "syswow64" ) { $REGSVR32 = "${Env:WINDIR}\syswow64\regsvr32" } Else { $REGSVR32 = "regsvr32" } - Start-Process "${REGSVR32}" -ArgumentList "/s ${dll}" -Wait + LogMsg "Register: ${dll}" + Try { Start-Process "${REGSVR32}" -ArgumentList "/s ${dll}" -Wait } + Catch { LogErr $_.Exception.Message } } } \ No newline at end of file diff --git a/Fix-WindowsUpdate.ps1 b/Fix-WindowsUpdate.ps1 index a9dd859..2a3a3c2 100644 --- a/Fix-WindowsUpdate.ps1 +++ b/Fix-WindowsUpdate.ps1 @@ -1,21 +1,48 @@ param([switch]$WSUS) +LogMsg "Fix-WindowsUpdate.ps1" + ## Delete any existing folder from a previous execution of this script -If ( Test-Path "${Env:WinDir}\SoftwareDistribution.old" ) { Remove-Item "${Env:WinDir}\SoftwareDistribution.old" -Recurse -Force } +If ( Test-Path "${Env:WinDir}\SoftwareDistribution.old" ) +{ + LogMsg "Deleting ""${Env:WinDir}\SoftwareDistribution.old""" + Try { Remove-Item "${Env:WinDir}\SoftwareDistribution.old" -Recurse -Force } + Catch { LogErr $_.Exception.Message } +} ## Stop Background Intelligent Transfer Services and Windows Update -Stop-Service BITS -Stop-Service wuauserv +LogMsg "Stopping BITS service" +Try { Stop-Service BITS } +Catch { LogErr $_.Exception.Message } +LogMsg "Stopping wuauserv service" +Try { Stop-Service wuauserv } +Catch { LogErr $_.Exception.Message } ## Rename the SoftwareDistribution folder, forcing Windows Update to recreate all metrics and redownload all updates -Rename-Item -Path "${Env:WinDir}\SoftwareDistribution" -NewName "${Env:WinDir}\SoftwareDistribution.old" -Force +LogMsg "Renaming ""${Env:WinDir}\SoftwareDistribution"" to ""${Env:WinDir}\SoftwareDistribution.old""" +Try { Rename-Item -Path "${Env:WinDir}\SoftwareDistribution" -NewName "${Env:WinDir}\SoftwareDistribution.old" -Force } +Catch { LogErr $_.Exception.Message } ## Start Windows Update and Background Intelligent Transfer Services -Start-Service wuauserv -Start-Service BITS +LogMsg "Starting wuauserv service" +Try { Start-Service wuauserv } +Catch { LogErr $_.Exception.Message } +LogMsg "Starting BITS service" +Try { Start-Service BITS } +Catch { LogErr $_.Exception.Message } ## Delete SoftwareDistribution.old from this execution of this script -If ( Test-Path "${Env:WinDir}\SoftwareDistribution.old" ) { Remove-Item "${Env:WinDir}\SoftwareDistribution.old" -Recurse -Force } +If ( Test-Path "${Env:WinDir}\SoftwareDistribution.old" ) +{ + LogMsg "Deleting ""${Env:WinDir}\SoftwareDistribution.old""" + Try { Remove-Item "${Env:WinDir}\SoftwareDistribution.old" -Recurse -Force } + Catch { LogErr $_.Exception.Message } +} ## If using WSUS, reset authorization with server and detect new updates -If ( $WSUS ) { Start-Process "${Env:WinDir}\System32\wuauctl.exe" -ArgumentList "/resetauthorization /detectnow" } \ No newline at end of file +If ( $WSUS ) +{ + LogMsg "Resetting WSUS authorization and starting update detection" + Try { Start-Process "${Env:WinDir}\System32\wuauctl.exe" -ArgumentList "/resetauthorization /detectnow" } + Catch { LogErr $_.Exception.Message } +} \ No newline at end of file diff --git a/Get-MemberOf.ps1 b/Get-MemberOf.ps1 deleted file mode 100644 index 06e4ffc..0000000 --- a/Get-MemberOf.ps1 +++ /dev/null @@ -1,34 +0,0 @@ -Function MemberOf() { - param( - [Parameter(Mandatory=$false)] - [switch]$Builtin=$false, - [Parameter(Mandatory=$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} - } - } - ([Security.Principal.WindowsPrincipal][System.Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole($Group) -} - -MemberOf -Group "administrators" \ No newline at end of file diff --git a/Get-NinjaAgentLogs.ps1 b/Get-NinjaAgentLogs.ps1 deleted file mode 100644 index e0bceab..0000000 --- a/Get-NinjaAgentLogs.ps1 +++ /dev/null @@ -1,21 +0,0 @@ -## Set the temporary directory used for uploading to FTP site -$TEMPDIR = "${Env:ProgramData}\Emberkom\Temp" -If (! (Test-Path -PathType Container $TEMPDIR) ) { New-Item -ItemType Directory -Force -Path $TEMPDIR } - -## Set the file name for the Ninja logs when it's uploaded -$NINJALOGS = "{0}_{1}.cab" -f ${Env:ComputerName}, $(Get-Date -Format "yyyyMMdd-HHmmss") - -## Get the NinjaRMM installation directory -If (Test-Path "${Env:ProgramFiles(x86)}") { - $INSTALLDIR = $(Get-ItemProperty -Path 'HKLM:\SOFTWARE\WOW6432Node\NinjaRMM LLC\NinjaRMMAgent' -Name Location).Location -} Else { - $INSTALLDIR = $(Get-ItemProperty -Path 'HKLM:\SOFTWARE\NinjaRMM LLC\NinjaRMMAgent' -Name Location).Location -} - -## Collect agent logs -Start-Process -FilePath "${INSTALLDIR}\ninjarmmagent.exe" -ArgumentList "/collectlogs" -Wait - -## Move ninjalogs.cab to $TEMPDIR -Move-Item -Path "${Env:WINDIR}\Temp\ninjalogs.cab" -Destination "${TEMPDIR}\${NINJALOGS}" - -## Upload to FTP \ No newline at end of file diff --git a/Get-SyncroUninstallCode.ps1 b/Get-SyncroUninstallCode.ps1 deleted file mode 100644 index a0eee59..0000000 --- a/Get-SyncroUninstallCode.ps1 +++ /dev/null @@ -1,7 +0,0 @@ -## Get SyncroMSP Uninstall Code -If ( Test-Path "${Env:ProgramFiles(x86)}" ) { - $UNINSTALL_CODE = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Wow6432Node\RepairTech\Syncro').uninstall_code -} Else { - $UNINSTALL_CODE = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\RepairTech\Syncro').uninstall_code -} -Write-Host $UNINSTALL_CODE \ No newline at end of file diff --git a/Install-AmazonCorretto.ps1 b/Install-AmazonCorretto.ps1 index e5f12eb..d326d18 100644 --- a/Install-AmazonCorretto.ps1 +++ b/Install-AmazonCorretto.ps1 @@ -1,16 +1,10 @@ -param( - [int]$Version=11 -) - -## Supported versions: 8 and 11 - -## Convert int to string -[string]$Version = $Version.ToString() +. "C:\Users\dyoder\Emberkom\Data\Projects\development\management-scripts\Tools.ps1" +## Amazon supported versions: 8 and 11 +$Version = "11" ## Get the correct URL -If ( Test-Path "${Env:ProgramFiles(x86)}" ) -{ $URL = "https://corretto.aws/downloads/latest/amazon-corretto-${Version}-x64-windows-jdk.msi" } -Else { $URL = "https://corretto.aws/downloads/latest/amazon-corretto-${Version}-x86-windows-jdk.msi" } +If ( Is64bit ) { $URL = "https://corretto.aws/downloads/latest/amazon-corretto-${Version}-x64-windows-jdk.msi" } +Else { $URL = "https://corretto.aws/downloads/latest/amazon-corretto-${Version}-x86-windows-jdk.msi" } ## Install Amazon Corretto -Start-Process -FilePath "msiexec.exe" -ArgumentList "/i ${URL} /qn /norestart" -Wait \ No newline at end of file +Install-Program -Path "msiexec.exe" -Arguments "/i ${URL} /qn /norestart" diff --git a/Install-BitDefender.ps1 b/Install-BitDefender.ps1 deleted file mode 100644 index 62c82af..0000000 --- a/Install-BitDefender.ps1 +++ /dev/null @@ -1,36 +0,0 @@ -[CmdletBinding()] -param( - [Parameter(Mandatory=$true)] - [string]$PackageID, - [Parameter(Mandatory=$false)] - [switch]$AllowReboot=$false -) - -## Set the reboot value -If ( $AllowReboot ) { $Reboot = '1' } Else { $Reboot = '0' } - -## URL to the BitDefender signed MSI archive -$BDSignedArchiveURL = 'http://download.bitdefender.com/business/misc/kb1695/eps_installer_signed.zip' - -## Set and create the local path to download the archive into -$DownloadDirectory = "${Env:TEMP}\bd-installer" - -## Delete any existing data and create a new empty $DownloadDirectory -If ( Test-Path $DownloadDirectory) { Remove-Item $DownloadDirectory -Recurse -Force } -New-Item -ItemType Directory -Path $DownloadDirectory -Force - -## Set the full path to the zip file we'll download -$BDZipArchive = "{0}\{1}" -f $DownloadDirectory,$(Split-Path -Path $BDSignedArchiveURL -Leaf) - -## Download the archive -(New-Object System.Net.WebClient).DownloadFile($BDSignedArchiveURL,$BDZipArchive) - -## Unzip the archive -Add-Type -Assembly “System.IO.Compression.FileSystem” -[IO.Compression.ZipFile]::ExtractToDirectory($BDZipArchive,$DownloadDirectory) - -## Get the MSI file -$MSI = (Get-ChildItem -Path $DownloadDirectory | Where { $_.Extension -ieq ".msi" }).FullName - -## Launch the installer -Start-Process "msiexec.exe" -ArgumentList "/i ${MSI} /qn GZ_PACKAGE_ID=${PackageID} REBOOT_IF_NEEDED=${Reboot}" -Wait diff --git a/Install-DeltekVision.ps1 b/Install-DeltekVision.ps1 index 8a87dcc..b40221c 100644 --- a/Install-DeltekVision.ps1 +++ b/Install-DeltekVision.ps1 @@ -4,8 +4,9 @@ $InstallLocation = "${Env:Public}\Desktop\Deltek Vision.lnk" ## Remove the existing shortcut If ( Test-Path $InstallLocation ) { + LogMsg "Deleting ""${InstallLocation}""" Try { Remove-Item -Path $InstallLocation -Force } - Catch { Write-Output $_.Exception.Message } + Catch { LogErr $_.Exception.Message } } ## Get the correct path to IE @@ -17,6 +18,7 @@ If ( $VisionURL ) ## Make sure IE exists where we expect it to If ( Test-Path $IEPATH ) { + LogMsg "Creating shortcut at ""${InstallLocation}""" Try { $WshShell = New-Object -ComObject WScript.Shell @@ -28,6 +30,6 @@ If ( $VisionURL ) $Shortcut.TargetPath = "${IEPATH}" $Shortcut.Save() } - Catch { Write-Output $_.Exception.Message } - } Else { Write-Output "Internet Explorer could not be found: ${IEPATH}" } -} Else { Write-Output "No URL to Deltek Vision was specified!" } + Catch { LogErr $_.Exception.Message } + } Else { LogMsg "Internet Explorer could not be found: ${IEPATH}" } +} Else { LogMsg "No URL to Deltek Vision was specified!" } diff --git a/Install-DisplayLink.ps1 b/Install-DisplayLink.ps1 index 09d410c..ba4e6d2 100644 --- a/Install-DisplayLink.ps1 +++ b/Install-DisplayLink.ps1 @@ -2,22 +2,19 @@ $BaseURL = 'https://dev.emberkom.com/emberkom/management-scripts/raw/branch/master/resources' ## Build URL for Windows 10 -If ( ([System.Environment]::OSVersion.Version).Major -ge 10 ) +If ( IsWindowsVersion -ge "10.0" ) { - If ( Test-Path "${Env:ProgramFiles(x86)}" ) - { $URL = '{0}/{1}' -f $BaseURL, 'DisplayLink_Win10RS_x64.msi' } - Else { $URL = '{0}/{1}' -f $BaseURL, 'DisplayLink_Win10RS_x86.msi' } + If ( Is64bit ) { $URL = '{0}/{1}' -f $BaseURL, 'DisplayLink_Win10RS_x64.msi' } + Else { $URL = '{0}/{1}' -f $BaseURL, 'DisplayLink_Win10RS_x86.msi' } } -## Build URL for Windows 7 -ElseIf ( (([System.Environment]::OSVersion.Version).Major -ge 7) -and (([System.Environment]::OSVersion.Version).Major -lt 10) ) +## Build URL for Windows 7, 8, and 8.1 +ElseIf ( (IsWindowsVersion -ge "6.1") -and (IsWindowsVersion -lt "10.0") ) { - If ( Test-Path "${Env:ProgramFiles(x86)}" ) - { $URL = '{0}/{1}' -f $BaseURL, 'DisplayLink_Win7-8.1_x64.msi' } - Else { $URL = '{0}/{1}' -f $BaseURL, 'DisplayLink_Win7-8.1_x86.msi' } + If ( Is64bit ) { $URL = '{0}/{1}' -f $BaseURL, 'DisplayLink_Win7-8.1_x64.msi' } + Else { $URL = '{0}/{1}' -f $BaseURL, 'DisplayLink_Win7-8.1_x86.msi' } } +Else { LogMsg "Operating system is not supported" ; Exit } - -## Install package -Write-Output "Installing: ${URL}" -Start-Process -FilePath "msiexec.exe" -ArgumentList "/i ${URL} /qn /norestart" -Wait \ No newline at end of file +## Install DisplayLink +Install-Program -Path "msiexec.exe" -Arguments "/i ${URL} /qn /norestart" diff --git a/Install-LiquidFilesOutlookAgent.ps1 b/Install-LiquidFilesOutlookAgent.ps1 index f968ac7..b6f84bc 100644 --- a/Install-LiquidFilesOutlookAgent.ps1 +++ b/Install-LiquidFilesOutlookAgent.ps1 @@ -6,12 +6,10 @@ $INSTALLER='https://dev.emberkom.com/emberkom/management-scripts/raw/branch/mast ## Set installer args If ( $URL ) { - Write-Output "LiquidFiles target server: ${URL}" + LogMsg "LiquidFiles target server: ${URL}" $INSTALLER_ARGS = "REGKEYSCRIPT=`"BaseUrl=${URL};`"" } Else { $INSTALLER_ARGS = '' } ## Run the installer -Write-Output "msiexec.exe /i ${INSTALLER} /qn /norestart ${INSTALLER_ARGS}" -Try { Start-Process -FilePath "msiexec.exe" -ArgumentList "/i ${INSTALLER} /qn /norestart ${INSTALLER_ARGS}" -Wait } -Catch { Write-Output $_.Exception.Message } \ No newline at end of file +Install-Program -Path "msiexec.exe" -Arguments "/i ${INSTALLER} /qn /norestart ${INSTALLER_ARGS}" diff --git a/Install-ManagementAgent.ps1 b/Install-ManagementAgent.ps1 index 3fc3044..c0fe7e9 100644 --- a/Install-ManagementAgent.ps1 +++ b/Install-ManagementAgent.ps1 @@ -1,76 +1,31 @@ -#[CmdletBinding()] -param( - [string]$TOKEN, - [int]$CUSTOMER_ID, - [int]$SOFTWARE_ID=101, - [string]$SERVER='manage.emberkom.com', - [string]$AGENT_FILENAME='EmberkomAgentSetup.exe' +param( + [Parameter(Mandatory=$true)][string]$TOKEN, + [Parameter(Mandatory=$true)][int]$CUSTOMER_ID, + [Parameter(Mandatory=$false)][int]$SOFTWARE_ID=101, + [Parameter(Mandatory=$false)][string]$SERVER='manage.emberkom.com', + [Parameter(Mandatory=$false)][string]$AGENT_FILENAME='EmberkomAgentSetup.exe' ) -## Immediately delete this script from disk -$THIS_SCRIPT = $MyInvocation.InvocationName -Try { Remove-Item $MyInvocation.InvocationName -Force } -Catch { Write-Output "This script tried to delete itself but failed!" } - -## Get temporary path -$TEMP = [System.IO.Path]::GetTempPath() - -## Setup log file and function to write to it -$LOGFILE = "{0}EmberkomAgentSetup_{1}.log" -f $TEMP, $(Get-Date -Format "yyyyMMddHHmmss") -If (! (Test-Path $LOGFILE) ) { New-Item -Path $LOGFILE -ItemType File | Out-Null; Write-Output "Log file: ${LOGFILE}" } -Function Write-Log([string]$message) -{ - $entry = "{0} : {1}" -f $(Get-Date -Format "yyyyMMddHHmmss"), $Message - Add-Content -Path $LOGFILE -Value $entry -} -Write-Log "Agent installation script has started" -Write-Log "CUSTOMER_ID: ${CUSTOMER_ID}" -Write-Log "SOFTWARE_ID: ${SOFTWARE_ID}" +## Source the Tools.ps1 script +Function SourceTools +{ . $([Scriptblock]::Create((New-Object Net.WebClient).DownloadString('https://dev.emberkom.com/emberkom/management-scripts/raw/branch/master/Tools.ps1'))) } +. SourceTools ## Build the path for $AGENT_INSTALLER -$AGENT_INSTALLER = "${TEMP}${AGENT_FILENAME}" -Write-Log "Agent installer will be saved to: ${AGENT_INSTALLER}" +$AGENT_INSTALLER = '{0}{1}' -f (GetTempPath), $AGENT_FILENAME -## Make sure the CUSTOMER_ID is specified -If ( $CUSTOMER_ID -and $TOKEN ) +## Get the right path to agent.exe based on the system bit-level +If ( Is64bit ) { $AGENT_EXE = "${Env:ProgramFiles(x86)}\N-able Technologies\Windows Agent\bin\agent.exe" } +Else { $AGENT_EXE = "${Env:ProgramFiles}\N-able Technologies\Windows Agent\bin\agent.exe" } + +## Make sure we need to install the agent +If ( !(Test-Path $AGENT_EXE) ) { - ## Get the right path to agent.exe based on the system bit-level - If ( Test-Path "${Env:ProgramFiles(x86)}" ) - { $AGENT_EXE = "${Env:ProgramFiles(x86)}\N-able Technologies\Windows Agent\bin\agent.exe" } - Else { $AGENT_EXE = "${Env:ProgramFiles}\N-able Technologies\Windows Agent\bin\agent.exe" } + ## Download agent and get path + $AGENT_INSTALLER = Download-File -URL 'https://manage.emberkom.com/download/2020.1.0.202/winnt/N-central/WindowsAgentSetup.exe' -File $AGENT_INSTALLER - ## Make sure we need to install the agent - If ( !(Test-Path $AGENT_EXE) ) - { - ## Build the AGENT_URL - $AGENT_URL = 'https://manage.emberkom.com/download/2020.1.0.202/winnt/N-central/WindowsAgentSetup.exe' + ## Install the agent + Install-Program $AGENT_INSTALLER -Arguments "/s /v"" /qn CUSTOMERID=${CUSTOMER_ID} CUSTOMERSPECIFIC=1 REGISTRATION_TOKEN=${TOKEN} SERVERPROTOCOL=HTTPS SERVERADDRESS=${SERVER} SERVERPORT=443""" -Delete - ## Delete $AGENT_INSTALLER if it already exists - If ( Test-Path $AGENT_INSTALLER ) - { - Write-Log "Deleting previous agent installer: ${AGENT_INSTALLER}" - Try { Remove-Item $AGENT_INSTALLER -Force } - Catch { Write-Log $_.Exception.Message } - } +} Else { LogMsg "The agent is already installed on this endpoint." } - ## Download the agent installer - Write-Log "Downloading agent installer from: ${AGENT_URL}" - Try { (New-Object System.Net.WebClient).DownloadFile($AGENT_URL, $AGENT_INSTALLER) } - Catch { Write-Log $_.Exception.Message ; Exit } - - ## Install the agent - Write-Log "Begin installing agent" - Try { Start-Process $AGENT_INSTALLER -ArgumentList "/s /v"" /qn CUSTOMERID=${CUSTOMER_ID} CUSTOMERSPECIFIC=1 REGISTRATION_TOKEN=${TOKEN} SERVERPROTOCOL=HTTPS SERVERADDRESS=${SERVER} SERVERPORT=443""" -Wait } - Catch { Write-Log $_.Exception.Message } - - ## Remove the agent installer - If ( Test-Path $AGENT_INSTALLER ) - { - Write-Log "Deleting agent installer: ${AGENT_INSTALLER}" - Try { Remove-Item -Path $AGENT_INSTALLER -Force } - Catch { Write-Log $_.Exception.Message } - } - - Write-Log "Agent installation script has finished" - } Else { Write-Log "The agent is already installed on this endpoint." } -} Else { Write-Log "No CUSTOMER_ID or TOKEN was specified!" } diff --git a/Install-MicrosoftTeams.ps1 b/Install-MicrosoftTeams.ps1 deleted file mode 100644 index 19d69c5..0000000 --- a/Install-MicrosoftTeams.ps1 +++ /dev/null @@ -1,7 +0,0 @@ -## Get the correct URL -If ( Test-Path "${Env:ProgramFiles(x86)}" ) -{ $URL = 'https://emberkom.s3.amazonaws.com/management/installers/Teams_windows_x64.msi' } -Else { $URL = 'https://emberkom.s3.amazonaws.com/management/installers/Teams_windows_x86.msi' } - -## Install Microsoft Teams -Start-Process -FilePath "msiexec.exe" -ArgumentList "/i ${URL} /qn /norestart" -Wait \ No newline at end of file diff --git a/Install-Nextcloud.ps1 b/Install-Nextcloud.ps1 index 0eacb1c..495671d 100644 --- a/Install-Nextcloud.ps1 +++ b/Install-Nextcloud.ps1 @@ -1,17 +1,12 @@ ## Define URL for downloading the installer $URL = 'https://dev.emberkom.com/emberkom/management-scripts/raw/branch/master/resources/Nextcloud-3.0.1-setup.exe' -$FILE = Split-Path $URL -Leaf +$FILE = '{0}{1}' -f (GetTempPath), (Split-Path $URL -Leaf) -## Remove previous package -If ( Test-Path $FILE ) { Remove-Item -Path $FILE -Force | Out-Null} - -## Download installer -Write-Output "Downloading: ${URL}" -Try { (New-Object System.Net.WebClient).DownloadFile($URL, $FILE) } -Catch { Write-Output $_.Exception.Message } +$FILE = Download-File -URL $URL -File $FILE ## Stop app if it's currently running -Get-Process | Where { $_.Name -like "nextcloud" } | Stop-Process -Force +Try { Get-Process | Where { $_.Name -like "nextcloud" } | Stop-Process -Force } +Catch { LogErr $_.Exception.Message } ## Get the install location so we can start the app again after installation If ( Test-Path "HKLM:SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Nextcloud" ) @@ -20,25 +15,12 @@ ElseIf ( Test-Path "HKLM:SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Nex { $InstallPath = '{0}\nextcloud.exe' -f $(Get-ItemProperty -Path "HKLM:SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Nextcloud" -ErrorAction SilentlyContinue).InstallLocation } ## Install package -If ( Test-Path $FILE ) -{ - Write-Output "Installing: ${FILE}" - Try { Start-Process -FilePath $FILE -ArgumentList "/S" -Wait } - Catch { $_.Exception.Message } -} -Else { Write-Output "${FILE} does not exist" } +Install-Program -Path $FILE -Arguments "/S" -Delete ## Start the app after installation If ( Test-Path $InstallPath ) { - Write-Output "Starting Nextcloud" - Start-Process $InstallPath -} - -## Delete installer package -If ( Test-Path $FILE ) -{ - Write-Output "Deleting ${FILE}" - Try { Remove-Item -Path $FILE -Force } - Catch { Write-Output $_.Exception.Message } + LogMsg "Starting Nextcloud" + Try { Start-Process $InstallPath } + Catch { LogErr $_.Exception.Message } } diff --git a/Install-O365BusinessRetail_x86_CurrentBranch_SkypeBusinessEntry_Auto.ps1 b/Install-O365BusinessRetail_x86_CurrentBranch_SkypeBusinessEntry_Auto.ps1 deleted file mode 100644 index 030f1c9..0000000 --- a/Install-O365BusinessRetail_x86_CurrentBranch_SkypeBusinessEntry_Auto.ps1 +++ /dev/null @@ -1,12 +0,0 @@ -If (!(Test-Path "${SystemDrive}\TEMP\Emberkom\odt2016")) { New-Item -ItemType Directory -Force -Path "${SystemDrive}\TEMP\Emberkom\odt2016" | Out-Null } -$config_source = "https://emberkom.s3.amazonaws.com/management/installers/odt2016/O365BusinessRetail_x86_CurrentBranch_SkypeBusinessEntry_Auto.xml" -$config_destination = "${SystemDrive}\TEMP\Emberkom\odt2016\configuration.xml" -$setup_source = "https://emberkom.s3.amazonaws.com/management/installers/odt2016/setup.exe" -$setup_destination = "${SystemDrive}\TEMP\Emberkom\odt2016\setup.exe" -If (Test-Path $config_destination) { Remove-Item $config_destination } -If (Test-Path $setup_destination) { Remove-Item $setup_destination } -Invoke-WebRequest $config_source -OutFile $config_destination -Invoke-WebRequest $setup_source -OutFile $setup_destination -Start-Process $setup_destination -ArgumentList "/configure ${config_destination}" -Wait -If (Test-Path $config_destination) { Remove-Item $config_destination } -If (Test-Path $setup_destination) { Remove-Item $setup_destination } \ No newline at end of file diff --git a/Install-OpenVPN.ps1 b/Install-OpenVPN.ps1 index 8723f11..3be4532 100644 --- a/Install-OpenVPN.ps1 +++ b/Install-OpenVPN.ps1 @@ -1,31 +1,23 @@ -## URL for Windows 10 -If ( ([System.Environment]::OSVersion.Version).Major -ge 10 ) -{ $URL = 'https://swupdate.openvpn.org/community/releases/openvpn-install-2.4.7-I607-Win10.exe' } +$OpenVPNVersion = "2.4.7" -## URL for Windows 7 -ElseIf ( (([System.Environment]::OSVersion.Version).Major -ge 7) -and (([System.Environment]::OSVersion.Version).Major -lt 10) ) -{ $URL = 'https://swupdate.openvpn.org/community/releases/openvpn-install-2.4.7-I607-Win7.exe' } +## Make sure we have an administrative token +If ( IsAdmin ) +{ + ## URL for Windows 10 + If ( IsWindowsVersion -ge "10.0" ) + { $URL = "https://swupdate.openvpn.org/community/releases/openvpn-install-${OpenVPNVersion}-I607-Win10.exe" } + + ## URL for Windows 7 + ElseIf ( (IsWindowsVersion -ge "7.0") -and (IsWindowsVersion -lt "10.0") ) + { $URL = "https://swupdate.openvpn.org/community/releases/openvpn-install-${OpenVPNVersion}-I607-Win7.exe" } + + ## Set the local filename + $FILE = '{0}{1}' -f (GetTempPath),(Split-Path $URL -Leaf) + + ## Download installer + $FILE = Download-File -URL $URL -File $FILE -## Set the local filename -$FILE = '{0}\{1}' -f $Env:TEMP,(Split-Path $URL -Leaf) - -## Remove previous package -If ( Test-Path $FILE ) { Remove-Item -Path $FILE -Force | Out-Null} - -## Download installer -Write-Output "Downloading: ${URL}" -Try { (New-Object System.Net.WebClient).DownloadFile($URL, $FILE) } -Catch { Write-Output $_.Exception.Message } - -## Install package -Write-Output "Installing: ${FILE}" -Try { Start-Process -FilePath $FILE -ArgumentList "/S" -Wait } -Catch { $_.Exception.Message } - -## Delete installer package -If ( Test-Path $FILE ) -{ - Write-Output "Deleting ${FILE}" - Try { Remove-Item -Path $FILE -Force } - Catch { Write-Output $_.Exception.Message } + ## Install package + Install-Program -Path $FILE -Arguments "/S" -Delete } +Else { LogMsg "Must be an administrator to install OpenVPN" } \ No newline at end of file diff --git a/Install-Scripts.ps1 b/Install-Scripts.ps1 deleted file mode 100644 index 2740670..0000000 --- a/Install-Scripts.ps1 +++ /dev/null @@ -1,23 +0,0 @@ -## Define the scripts and URLs to them -$URLS = @( - 'https://emberkom.s3.amazonaws.com/management/scripts/Upload-Contents.ps1' - ) - -## Define and prepare the main script directory -$SCRIPT_DIRECTORY = "${Env:ProgramData}\Emberkom\Scripts" -if (!(Test-Path $SCRIPT_DIRECTORY)) { New-Item -ItemType Directory -Path $SCRIPT_DIRECTORY } - -## Loop through each URL -ForEach ($url in $URLS) { - ## Set the script name based on the URL path - $SCRIPT_FILE = $($url.Split('/') | Select-Object -Last 1) - - ## Delete any previous version of the script - If ( Test-Path "${SCRIPT_DIRECTORY}\${SCRIPT_FILE}" ) { - try { Remove-Item -Path "${SCRIPT_DIRECTORY}\${SCRIPT_FILE}" } - catch { Write-Host "Could not delete ${SCRIPT_DIRECTORY}\${SCRIPT_FILE}"; exit } } - - ## Download latest version of script - If ( !( Test-Path "${SCRIPT_DIRECTORY}\${SCRIPT_FILE}" )) { - try { (New-Object System.Net.WebClient).DownloadFile($url,"${SCRIPT_DIRECTORY}\${SCRIPT_FILE}") } - catch { Write-Host "Failed to download ${url}" } } } diff --git a/Install-SketchUp.ps1 b/Install-SketchUp.ps1 index 3927f66..e296768 100644 --- a/Install-SketchUp.ps1 +++ b/Install-SketchUp.ps1 @@ -1,56 +1,54 @@ -## Uninstall SketchUp 2016 -If ( Test-Path "${Env:ProgramFiles}\SketchUp\SketchUp 2016\SketchUp.exe" ) +## Version of SketchUp to install +$InstallVersion = "2020" + +## Make sure we have an administrative token +If ( IsAdmin ) { - Write-Output "Uninstalling SketchUp 2016..." - Try { Start-Process "msiexec.exe" -ArgumentList '/X{D87EE6DC-32BA-4219-AC75-0A6FD54ED058} /qn /norestart' -Wait } - Catch { Write-Output $_.Exception.Message } -} - -## Uninstall SketchUp 2017 -If ( Test-Path "${Env:ProgramFiles}\SketchUp\SketchUp 2017\SketchUp.exe" ) -{ - Write-Output "Uninstalling SketchUp 2017..." - Try { Start-Process "msiexec.exe" -ArgumentList '/X{E59BD84C-169B-4F3F-AC5D-85127CF67051} /qn /norestart' -Wait } - Catch { Write-Output $_.Exception.Message } -} - -## Uninstall SketchUp 2019 -If ( Test-Path "${Env:ProgramFiles}\SketchUp\SketchUp 2019\SketchUp.exe" ) -{ - Write-Output "Uninstalling SketchUp 2019..." - Try { Start-Process "msiexec.exe" -ArgumentList '/X{06964675-EB01-6D18-6704-429DE73A8319} /qn /norestart' -Wait } - Catch { Write-Output $_.Exception.Message } -} - -## Uninstall SketchUp 2020 -If ( Test-Path "${Env:ProgramFiles}\SketchUp\SketchUp 2020\SketchUp.exe" ) -{ - Write-Output "Uninstalling SketchUp 2020..." - Try { Start-Process "msiexec.exe" -ArgumentList '/X{5778f9a3-781e-16f1-a6bf-08fd59dfa77b} /qn /norestart' -Wait } - Catch { Write-Output $_.Exception.Message } -} - -## Define URL for downloading the installer -$URL = 'https://www.sketchup.com/sketchup/2020/SketchUpPro-exe' -$FILE = '{0}\{1}.exe' -f $Env:TEMP,(Split-Path $URL -Leaf) - -## Remove previous package -If ( Test-Path $FILE ) { Remove-Item -Path $FILE -Force | Out-Null} - -## Download installer -Write-Output "Downloading: ${URL}" -Try { (New-Object System.Net.WebClient).DownloadFile($URL, $FILE) } -Catch { Write-Output $_.Exception.Message } - -## Install package -Write-Output "Installing: ${FILE}" -Try { Start-Process -FilePath $FILE -ArgumentList "/silent" -Wait } -Catch { $_.Exception.Message } - -## Delete installer package -If ( Test-Path $FILE ) -{ - Write-Output "Deleting ${FILE}" - Try { Remove-Item -Path $FILE -Force } - Catch { Write-Output $_.Exception.Message } + ## Define URL for downloading the installer + $URL = "https://www.sketchup.com/sketchup/${InstallVersion}/SketchUpPro-exe" + + ## Make sure the URL is valid before we do anything + If ( IsURLValid $URL ) + { + ## Uninstall SketchUp 2016 + If ( Test-Path "${Env:ProgramFiles}\SketchUp\SketchUp 2016\SketchUp.exe" ) + { + LogMsg "Uninstalling SketchUp 2016" + Try { Start-Process "msiexec.exe" -ArgumentList '/X{D87EE6DC-32BA-4219-AC75-0A6FD54ED058} /qn /norestart' -Wait } + Catch { LogErr $_.Exception.Message } + } + + ## Uninstall SketchUp 2017 + If ( Test-Path "${Env:ProgramFiles}\SketchUp\SketchUp 2017\SketchUp.exe" ) + { + LogMsg "Uninstalling SketchUp 2017" + Try { Start-Process "msiexec.exe" -ArgumentList '/X{E59BD84C-169B-4F3F-AC5D-85127CF67051} /qn /norestart' -Wait } + Catch { LogErr $_.Exception.Message } + } + + ## Uninstall SketchUp 2019 + If ( Test-Path "${Env:ProgramFiles}\SketchUp\SketchUp 2019\SketchUp.exe" ) + { + LogMsg "Uninstalling SketchUp 2019" + Try { Start-Process "msiexec.exe" -ArgumentList '/X{06964675-EB01-6D18-6704-429DE73A8319} /qn /norestart' -Wait } + Catch { LogErr $_.Exception.Message } + } + + ## Uninstall SketchUp 2020 + If ( Test-Path "${Env:ProgramFiles}\SketchUp\SketchUp 2020\SketchUp.exe" ) + { + LogMsg "Uninstalling SketchUp 2020" + Try { Start-Process "msiexec.exe" -ArgumentList '/X{5778f9a3-781e-16f1-a6bf-08fd59dfa77b} /qn /norestart' -Wait } + Catch { LogErr $_.Exception.Message } + } + + ## Set the local file name to download to + $FILE = '{0}{1}.exe' -f (GetTempPath),(Split-Path $URL -Leaf) + + ## Download installer + $FILE = Download-File -URL $URL -File $FILE + + ## Install package + Install-Program -Path $FILE -Arguments "/silent" -Delete + } } diff --git a/Install-VLC.ps1 b/Install-VLC.ps1 index 3ce0d2e..3c8f13c 100644 --- a/Install-VLC.ps1 +++ b/Install-VLC.ps1 @@ -1,27 +1,13 @@ -. $([Scriptblock]::Create((New-Object Net.WebClient).DownloadString('https://dev.emberkom.com/emberkom/management-scripts/raw/branch/master/Tools.ps1'))) - -## Make sure we're running as admin +## Make sure we have an administrative token If ( IsAdmin ) { ## Get the correct URL - If ( Is64bit) - { $URL = 'https://get.videolan.org/vlc/3.0.11/win64/vlc-3.0.11-win64.exe' } - Else - { $URL = 'https://ftp.osuosl.org/pub/videolan/vlc/3.0.11/win32/vlc-3.0.11-win32.exe' } + If ( Is64bit) { $URL = 'https://get.videolan.org/vlc/3.0.11/win64/vlc-3.0.11-win64.exe' } + Else { $URL = 'https://ftp.osuosl.org/pub/videolan/vlc/3.0.11/win32/vlc-3.0.11-win32.exe' } ## Download file and get local file name $Installer = Download-File $URL - - If ( Test-Path $Installer ) - { - ## Run silent install - Try { Start-Process $Installer -ArgumentList "/S" -Wait } - Catch { Write-Output $_.Exception.Message } - ## Delete the file we downloaded - Try { Remove-Item $Installer -Force } - Catch { Write-Output $_.Exception.Message } - } - Else { Write-Output "The URL was not downloaded correctly: ${URL}" } + If ( $Installer ) { Install-Program -Path "${Installer}" -Arguments "/S" -Delete } } -Else { Write-Output "You must run this script as an administrator" } \ No newline at end of file +Else { LogMsg "Must be an administrator to install VLC" } \ No newline at end of file diff --git a/Install-ZeroTier.ps1 b/Install-ZeroTier.ps1 index 6ba65af..ffe0e90 100644 --- a/Install-ZeroTier.ps1 +++ b/Install-ZeroTier.ps1 @@ -1,77 +1,80 @@ -param( - [string]$JoinNetwork -) - -## Only specify a network ID here if it isn't specified in an environment variable (RMM or endpoint) or you need to override that value: -$JoinNetwork = '' +param([string]$JoinNetwork = '') ## If $JoinNetwork is not specified at the command line, use the ZTNetworkID customer custom field if it exists -If ( (-not $JoinNetwork) -and ($ZeroTierNetworkID) ) { $JoinNetwork = $ZeroTierNetworkID } - -## Get Windows version -$WinVersion = [double]("{0}.{1}" -f ([System.Environment]::OSVersion.Version).Major,([System.Environment]::OSVersion.Version).Minor) +If ( ($JoinNetwork = '') -and ($ZeroTierNetworkID) ) { $JoinNetwork = $ZeroTierNetworkID } ## Make sure we're running at least Windows 7 -If ( $WinVersion -ge 6.1 ) { - +If ( IsWindowsVersion -ge "6.1" ) +{ ## Specify the ZeroTier One MSI installer URL $URL = 'https://download.zerotier.com/dist/ZeroTier%20One.msi' ## Install ZeroTier One - Start-Process "msiexec.exe" -ArgumentList "/i ${URL} /qn /norestart" -Wait + Install-Program "msiexec.exe" -Arguments "/i ${URL} /qn /norestart" ## Make sure there's a network to join before attempting to start the ZeroTierOneService or join a network - If ( $JoinNetwork ) { - + If ( $JoinNetwork ) + { ## This will be used to determine whether or not the service was successfully started $ServiceRunning = $false ## Check to make sure the ZeroTierOneService has started ## We'll only loop through this for a few seconds before failing - For ( $i = 1 ; $i -le 5 ; $i++ ) { - + LogMsg "Attempting to start the ZeroTierOneService service..." + For ( $i = 1 ; $i -le 5 ; $i++ ) + { ## Check to see if the service is running - If ( (Get-Service -Name ZeroTierOneService).Status -ne "Running" ) { - + If ( (Get-Service -Name ZeroTierOneService).Status -ne "Running" ) + { ## Attempt to stop/start the service - Restart-Service -Name ZeroTierOneService -Force + Try { Restart-Service -Name ZeroTierOneService -Force } + Catch { LogErr $_.Exception.Message } ## Wait a few seconds before checking again Start-Sleep -Seconds 5 } ## If the service is running, break the loop - Else { $ServiceRunning = $true ; break } + Else + { + LogMsg " ZeroTierOneService service is started" + $ServiceRunning = $true ; break + } } ## Make sure the service is running before attempting to join a network - If ( $ServiceRunning ) { - + If ( $ServiceRunning ) + { ## Set the path to the ZeroTier installation directory - If ( Test-Path "${Env:ProgramFiles(x86)}" ) { $ZTPath = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\WOW6432Node\ZeroTier, Inc.\ZeroTier One').Path } - Else { $ZTPath = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\ZeroTier, Inc.\ZeroTier One').Path } + If ( Is64bit ) { $ZTPath = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\WOW6432Node\ZeroTier, Inc.\ZeroTier One').Path } + Else { $ZTPath = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\ZeroTier, Inc.\ZeroTier One').Path } ## Make sure the path actually exists - If ( Test-Path $ZTPath ) { - - $ZTcli = "${ZTPath}\zerotier-cli.bat" - + $ZTcli = "${ZTPath}\zerotier-cli.bat" + If ( Test-Path "${ZTcli}" ) + { ## Join the network, if $ZTcli exists - If ( Test-Path $ZTcli ) { Start-Process $ZTcli -ArgumentList "join ${JoinNetwork}" -Wait } - - ## Otherwise write an error message - Else { Write-Host "Could not find zerotier-cli" } - - } Else { Write-Host "ZeroTier may not be installed correctly" } + LogMsg "Joining ZeroTier network ${JoinNetwork}" + Try { Start-Process $ZTcli -ArgumentList "join ${JoinNetwork}" -Wait } + Catch { LogErr $_.Exception.Message } + } + Else { LogMsg "Could not find ""${ZTcli}""" } } ## If the service still isn't running, just error out - Else { Write-Host "ZeroTierOneService service could not be started" } + Else { LogMsg " ZeroTierOneService could not be started in a timely fashion" } - } Else { Write-Host "A network to join was not specified" } + } + Else { LogMsg "A ZeroTier network ID was not specified, will not join any network" } ## Remove the ZeroTier One Start Menu shortcut $ShortcutPath = "${ProgramData}\Microsoft\Windows\Start Menu\Programs\ZeroTier One.lnk" - If ( Test-Path $ShortcutPath ) { Remove-Item $ShortcutPath -Force } + If ( Test-Path $ShortcutPath ) + { + LogMsg "Deleting Start Menu shortcut from ""${ShortcutPath}""" + Try { Remove-Item $ShortcutPath -Force } + Catch { LogErr $_.Exception.Message } + } -} Else { Write-Host "ZeroTier requires at least Windows 7 to function properly" } +} +Else { LogMsg "ZeroTier can only be installed on Windows 7 or higher operating systems" } diff --git a/Remediation-RestartServices.ps1 b/Remediation-RestartServices.ps1 index 3870a54..402ce63 100644 --- a/Remediation-RestartServices.ps1 +++ b/Remediation-RestartServices.ps1 @@ -1,30 +1,53 @@ -Function Remediation-RestartServices +Function Remediation-RestartService { -param( - [Int32]$Wait=0, - [Parameter(Mandatory=$true)] - [string]$Services -) - -## Wait for the specIfied amount of time before proceeding -If ( $Wait -gt 0 ) { Start-Sleep -Seconds $Wait } - -##Split the list of services so we can process each one -$Services.Split(",") | ForEach { - - ## Get the service's status - $service = $_ - $status = (Get-Service -Name $service -ErrorAction SilentlyContinue).Status - - ## Make sure the service exists - If ( $status ) { - - ## Try to restart the service - Write-Output "Restarting ${service}" - Try { Restart-Service -Name $service -Force -ErrorAction SilentlyContinue } - Catch { Write-Output $_ } - - } Else { Write-Output "${service} does not exist" } - +param([Parameter(Mandatory=$true,ValueFromPipeline=$true)][string[]]$Name) +ForEach ( $service in $Name ) +{ + Remediation-StopService -Name $service } -} \ No newline at end of file +} + +Function Remediation-StopService +{ +param([Parameter(Mandatory=$true,ValueFromPipeline=$true)][string[]]$Name) +ForEach ( $service in $Name ) +{ + $status = (Get-Service -Name $service -ErrorAction SilentlyContinue).Status + If ( $status -ne "Stopped" ) + { + LogMsg " Stopping '${service}'" + Try { Stop-Service -Name $service -Force -ErrorAction SilentlyContinue } + Catch { LogErr $_.Exception.Message } + } + Else { LogMsg " '${service}' service is already stopped" } +} +} + +Function Remediation-StartService +{ +param([Parameter(Mandatory=$true,ValueFromPipeline=$true)][string[]]$Name) +ForEach ( $service in $Name ) +{ + $service = "bogus" + $status = (Get-Service -Name $service -ErrorAction SilentlyContinue).Status + If ( !($status) ) + { + Write-Host "Cannot find the service '${service}', attempting to match a service display name instead" + $status = Get-Service | Where { $_.DisplayName -match $service } + Write-Host $status + } + Else { Write-Host "Status is: ${status}" } + If ( $status -eq "StartPending" ) + { LogMsg " '${service}' was previously started, and is still starting up" } + ElseIf ( $status -ne "Running" ) + { + LogMsg " Starting '${service}'" + Try { Start-Service -Name $service -Force -ErrorAction SilentlyContinue } + Catch { LogErr $_.Exception.Message } + } + Else { LogMsg " '${service}' service is already running" } +} +} + +[string[]]$list = "apple", "orange", "banana", "pineapple" +Write-Host "Here are the list items: ${list}" \ No newline at end of file diff --git a/Tools.ps1 b/Tools.ps1 index 063736c..4071d1e 100644 --- a/Tools.ps1 +++ b/Tools.ps1 @@ -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) +}