Skip to content

Instantly share code, notes, and snippets.

@karlgluck
Created May 15, 2022 19:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karlgluck/5506bae9008e2015334d514e5760cdaf to your computer and use it in GitHub Desktop.
Save karlgluck/5506bae9008e2015334d514e5760cdaf to your computer and use it in GitHub Desktop.
How to register a script block to run with elevated privileges when the current user logs in
$JobName = "RunAtLoginExample"
$Enabled = $True # set to $False and run to remove the job
# https://stackoverflow.com/questions/40569045/register-scheduledjob-as-the-system-account-without-having-to-pass-in-credentia
# Output: %LOCALAPPDATA%\Microsoft\Windows\PowerShell\ScheduledJobs\$JobName
$accountId = ((Get-WMIObject -class Win32_ComputerSystem | Select-Object -ExpandProperty username))
$Trigger = New-JobTrigger -AtLogOn
$JobOptions = New-ScheduledJobOption -StartIfOnBattery -RunElevated
$Task = Get-ScheduledJob -Name $JobName -ErrorAction SilentlyContinue
if ($Task -ne $null)
{
Unregister-ScheduledJob $Task -Confirm:$False
}
if ($Enabled)
{
Register-ScheduledJob -Name $JobName -Trigger $Trigger -ScheduledJobOption $JobOptions -ScriptBlock { "$($env:USERNAME) at $(Get-Date)" | Out-File -FilePath "C:\RunAtStartup.txt" } #| Out-Null
$TaskPrincipal = New-ScheduledTaskPrincipal -UserID $accountId -LogonType Interactive -RunLevel Highest
Set-ScheduledTask -TaskPath '\Microsoft\Windows\PowerShell\ScheduledJobs' -TaskName $JobName -Principal $TaskPrincipal #| Out-Null
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment