Last active
November 19, 2021 17:45
-
-
Save it3xl/c897b2c054e8ed19eb687bd1b9bfbb4c to your computer and use it in GitHub Desktop.
Set startup account of a Scheduled job in PowerShell. See https://stackoverflow.com/questions/40569045/register-scheduledjob-as-the-system-account-without-having-to-pass-in-credentia/60554216#60554216
This file contains hidden or 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
# For https://stackoverflow.com/questions/40569045/register-scheduledjob-as-the-system-account-without-having-to-pass-in-credentia/60554216#60554216 | |
$ErrorActionPreference = 'Stop' | |
Clear-Host | |
#### Start of Main Logic ########################### | |
$taskName = "my_PowerShell_job" | |
$accountId = "NT AUTHORITY\SYSTEM"; | |
#$accountId = "NT AUTHORITY\LOCAL SERVICE"; | |
$task = Get-ScheduledJob -Name $taskName -ErrorAction SilentlyContinue | |
if ($task -ne $null) | |
{ | |
Unregister-ScheduledJob $task -Confirm:$false | |
Write-Host " @ The old ""$taskName"" PowerShell job has been unregistered"; Write-Host; | |
} | |
# Uncomment the following exit command to only delete your job. | |
# exit; | |
# Shchedule your job. Using of -AtStartup as an example. | |
$trigger = New-JobTrigger -AtStartup; | |
$options = New-ScheduledJobOption -StartIfOnBattery -RunElevated; | |
Write-Host " @ Registering of ""$taskName"" job"; | |
Register-ScheduledJob -Name $taskName -Trigger $trigger -ScheduledJobOption $options ` | |
-ScriptBlock { | |
# Put your code here. | |
Write-Host Your job has been launched!; | |
} | |
$principal = New-ScheduledTaskPrincipal -UserID $accountId ` | |
-LogonType ServiceAccount -RunLevel Highest; | |
$psJobsPathInScheduler = "\Microsoft\Windows\PowerShell\ScheduledJobs"; | |
$someResult = Set-ScheduledTask -TaskPath $psJobsPathInScheduler ` | |
-TaskName $taskName -Principal $principal | |
#### End of Main Logic ########################### | |
Write-Host; | |
Write-Host " @ Let's look at running account of ""$taskName"" PowerShell job" | |
$task = Get-ScheduledTask -TaskName $taskName | |
$task.Principal | |
Write-Host " @ Let's start ""$taskName"" manually" | |
Start-Job -DefinitionName $taskName | Format-Table | |
Write-Host " @ Let's proof that ""$taskName"" PowerShell job has been launched"; Write-Host; | |
Start-Sleep -Seconds 3 | |
Receive-Job -Name $taskName | |
Write-Host; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment