Windows Server

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.

2 replies »

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 )

Twitter picture

You are commenting using your Twitter 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.