Execution Context:
Updated Windows 10 Pro workstation
PowerShell 7 & 5.1 (trying in both contexts)
I’ve been running PowerShell scheduled jobs for years (specifically, not Scheduled Tasks). So I am comfortable with the basics of scheduled job registration and execution. However recently I’ve attempted to implement a scheduled job using a switch parameter with no success. My question to the forum is whether anyone else has had success with this specific case and, if so, what method(s) were used (provide a Register-ScheduledJob cmdlet example)? My analysis indicates that I am not registering my scheduled job with its switch parameter correctly but I have not been able to decipher the correct syntax for that.
At the bottom is a test script I am using for diagnostic tests.
Notes:
This script works both interactively (with the switch parameter active) and as a scheduled job (with the Param commented out).
The CmdletBinging/Param segment is commented out as a success baseline.
Success is determined by simple Add-Content output generation to the designated log file.
I register the scheduled job using: "Register-ScheduledJob -Name JobTest -FilePath “C:\Jobs\JobTest.ps1”.
I run the test job by opening the Windows Task Scheduler UI, navigating to “Task Scheduler Library\Microsoft\Windows\PowerShell\ScheduledJobs” and right-clicking the JobTest job (created via the Register-ScheduledJob cmdlet) to select “Run”.
When I uncomment the switch parameter declaration I can provide the switch parameter on a command line to execute interactively without issue.
The issue arises when I attempt to run the registered scheduled job.
Here is a list of a subset of testing results with variations, all involved execution of the script as a scheduled job with the switch param declaration uncommented:
- No switch parameter provided to the Register-ScheduledJob cmdlet - The job shows running indefinitely with no output to the log.
- Supply the "-ArchiveAll" switch (tried both with and without quotes) to the Register-ScheduledJob cmdlet with -ArgumentList - Job runs, terminates, no log output.
- Register-ScheduledJob -ScriptBlock { & "C:\jobs\JobTest.ps1 -ArchiveAll" } - no log output
#[CmdletBinding()] #Param ( #[Parameter(Mandatory = $true, Position = 0)] #[switch]$ArchiveAll = $false #)Set-Variable -Name LogFile -Value “D:\Logs\JobTest.log”
Add-Content -Path $LogFile -Value “Starting script execution”
if ($ArchiveAll) {
Add-Content -Path $LogFile -Value “Archive all flag is set”
}
Add-Content -Path $LogFile -Value “Execution ended.”