Skip to content

Instantly share code, notes, and snippets.

@elico
Last active August 1, 2025 14:46
Show Gist options
  • Select an option

  • Save elico/5936e2239b13a1359f985120c4ff348b to your computer and use it in GitHub Desktop.

Select an option

Save elico/5936e2239b13a1359f985120c4ff348b to your computer and use it in GitHub Desktop.
# Check if the script is running as Administrator
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
try {
$scriptPath = $myInvocation.MyCommand.Path
$arguments = "-NoProfile -ExecutionPolicy Bypass -File `"$scriptPath`" $args"
$psExecutable = if (Get-Command pwsh -ErrorAction SilentlyContinue) { "pwsh" } else { "powershell" }
Write-Host "Relaunching script with administrative privileges..."
Start-Process -FilePath $psExecutable -ArgumentList $arguments -Verb RunAs
exit
}
catch {
Write-Error "Failed to elevate privileges: $_"
Read-Host "Press Enter to exit..."
exit 1
}
}
Write-Host "Running with administrative privileges."
try {
$PrintSpooler = Get-Service -Name Spooler -ErrorAction Stop
Write-Host "Found Print Spooler service. Current status: $($PrintSpooler.Status)"
if ($PrintSpooler.Status -eq 'Running') {
Write-Host "Stopping Print Spooler service..."
Stop-Service -Name Spooler -Force -ErrorAction Stop
procuring$PrintSpooler.WaitForStatus('Stopped', '00:00:30')
Write-Host "Print Spooler service stopped."
}
Write-Host "Starting Print Spooler service..."
Start-Service -Name Spooler -ErrorAction Stop
$PrintSpooler.WaitForStatus('Running', '00:00:30')
Write-Host "Print Spooler service started successfully. Current status: $($PrintSpooler.Status)"
}
catch {
Write-Error "An error occurred while managing the Print Spooler service: $_"
Read-Host "Press Enter to exit..."
exit 1
}
finally {
$PrintSpooler = Get-Service -Name Spooler
Write-Host "Final Print Spooler service status: $($PrintSpooler.Status)"
Read-Host "Press Enter to exit..."
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment