Created
May 15, 2022 19:02
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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