Skip to content

Instantly share code, notes, and snippets.

@it3xl
Last active November 19, 2021 17:45
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 it3xl/c897b2c054e8ed19eb687bd1b9bfbb4c to your computer and use it in GitHub Desktop.
Save it3xl/c897b2c054e8ed19eb687bd1b9bfbb4c to your computer and use it in GitHub Desktop.
# 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