PowerShell

How to implement your PowerShell 7 Scripts in Task Scheduler

So you’re already working with the latest PowerShell version and wondering how to automate your PowerShell 7 scripts with the task scheduler? Yes? Ok, then stay tuned I will show you two ways to include a PS7 script in the task scheduler. Let’s dive in.

Option 1

In this section I will wrap my PowerShell script in a PowerShell 5 Scheduled Job. Note that a PowerShell 5 scheduled job will be generated and your PS7 script will be executed from this PS5 task.

Here is an example of how to work this out.

# Option 1: PowerShell 7 wrapped in PowerShell 5 ScheduledJobs

Register-ScheduledJob -Name Test1 -ScriptBlock {pwsh.exe $home\script.ps1} `
-Trigger (New-JobTrigger -Once -At (Get-Date) `
-RepetitionInterval (New-TimeSpan -Minutes 15) `
-RepeatIndefinitely)

Option 2 (recommended)

In this option I am going to show you the creation of a scheduled taks for your PowerShell 7 script. This is the recommended option because your script will be executed more directly without using PowerShell 5 in the background.

# Option 2: Scheduled-Task

$Action = New-ScheduledTaskAction -Execute `
"pwsh –Noprofile -WindowStyle Hidden -ExecutionPolicy Bypass -File $home\script.ps1"
$Trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) `
-RepetitionInterval (New-TimeSpan -Minutes 15)
$Principal = New-ScheduledTaskPrincipal -UserId pagr\administrator
$Task = New-ScheduledTask -Action $Action -Trigger $Trigger -Principal $Principal
Register-ScheduledTask -TaskName "Test4" -InputObject $Task -Force

Conclusion

Option 1 and Option 2 do the same thing. However, option 2 will start the task and the script where it should start, in Powershell 7.

3 replies »

  1. in pwsh 7.2.9 for task scheduler the action is not
    -File C:\SomeDir\SomeScript.ps1
    -File C:\\SomeDir\\SomeScript.ps1
    All websites and all my books were wrong.
    It took me 8 hours to figure that out because
    my Windows 10 event viewer is broken and
    the script I was using was to start solarwinds event log forwarder and solarwinds kiwi syslogd so I never saw the error
    because I left them shutdown.
    Maybe …i could have picked it up with get-winevent or get-eventlog
    but, it is fixed now. it could be a bug in pwsh
    i will have to escalate to the pwsh folks to let them deal with it.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.