#What you need before you start
- A script that works when you run it by hand. Microsoft's troubleshooting page puts this first: "a complete script is the prerequisite to configure a scheduled task." Run it once in a PowerShell window, as the account the task will use.
- The account it runs as. A task that copies to a share on another server needs a domain account with rights on that share. Keep it to the rights the job needs.
- Windows PowerShell 5.1 (
powershell.exe) is what this post uses, because every Windows server has it. For PowerShell 7, the program ispwsh.exeand the switches are in about_Pwsh. - The ScheduledTasks cmdlets, for the PowerShell way. Microsoft documents them for Windows Server 2016, 2019, 2022 and 2025.
#Step 1: a script that says when it failed
Most 0x1 threads start with a script that failed and left nothing behind. This one sends yesterday's sales file from a store server to head office, keeps a transcript, and ends with exit code 0 or 1 on purpose. The paths are invented: put in your own.
# C:\Scripts\Send-SalesFile.ps1
param(
[string]$Source = 'D:\POS\Export',
[string]$Target = '\\hq-files\sales\inbox'
)
$ErrorActionPreference = 'Stop'
$logFolder = 'C:\Scripts\Logs'
New-Item -ItemType Directory -Path $logFolder -Force | Out-Null
$log = Join-Path $logFolder ("Send-SalesFile_{0:yyyyMMdd}.log" -f (Get-Date))
Start-Transcript -Path $log -Append | Out-Null
$code = 0
try {
$day = (Get-Date).AddDays(-1).ToString('yyyyMMdd')
$file = Join-Path $Source "SALES_$day.csv"
if (-not (Test-Path -Path $file)) { throw "No sales file for $day in $Source" }
$rows = (Import-Csv -Path $file | Measure-Object).Count
if ($rows -eq 0) { throw "$file has no rows" }
Copy-Item -Path $file -Destination $Target -Force
Write-Output "Sent $file with $rows rows to $Target"
}
catch {
Write-Output "FAILED: $($_.Exception.Message)"
$code = 1
}
finally {
Stop-Transcript | Out-Null
}
exit $codeThree choices in it matter later:
$ErrorActionPreference = 'Stop'turns an error in any command into one thecatchsees, instead of a red line nobody reads.- The
throwlines make "nothing to send" a failure. A missing file is the night you most need to hear about. exit $codeis the exit code Task Scheduler records. Without it, a script that caught its own error ends with 0, and the task looks fine.
#Step 2: create the task in Task Scheduler
Use Create Task rather than Create Basic Task: the wizard sets most properties to their defaults and hides the ones below.
- Open Task Scheduler (
taskschd.msc). To keep your tasks apart from Windows' own, select Task Scheduler Library in the console tree, click New Folder in the Actions pane, name itRetailand select it. - In the Actions pane, click Create Task.
- On the General tab, enter a Name,
Send sales file. Under Security options, click Change User or Group and choose the account from the list above. - Select Run whether user is logged on or not. Leave Do not store password cleared: Microsoft's page on task security says that with it, the task "can only use the security context to access local resources", and a task that needs a network share fails.
- On the Triggers tab, click New…, choose On a schedule, Daily, and a start time such as 02:30. Click OK.
- On the Actions tab, click New…. Action is Start a program. Fill in the three fields:
| Field | What to put in it |
|---|---|
| Program/script | powershell.exe |
| Add arguments (optional) | -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "C:\Scripts\Send-SalesFile.ps1" |
| Start in (optional) | C:\Scripts |
- On the Settings tab, select Run task as soon as possible after a scheduled start is missed (Microsoft's page says the service waits ten minutes before starting a missed task), set Stop the task if it runs longer than to 1 hour, and under If the task is already running choose Do not start a new instance.
- Click OK and type the account's password when asked.
- Right-click the task and choose Run to test it now, then refresh the list and read Last Run Result.
Why those arguments, from about_PowerShell_exe:
-File"must be the last parameter in the command". Everything after it goes to the script, so a switch written after the path is passed to your script, not to PowerShell.-NonInteractiveis meant for "scripts that run in scheduled tasks". ARead-Hostor confirmation prompt becomes an error instead of a task that hangs until the time limit.-ExecutionPolicy Bypasssets the policy for this session only and "does not change the PowerShell execution policy that's set in the registry".-NoProfileskips the account's profile, so the task runs the same way whoever's profile it is.
Start in matters because without a working directory, Microsoft's cmdlet reference says the task runs in %windir%\system32. A script that opens .\stores.csv looks for it there.
#Step 3: the same task with Register-ScheduledTask
The same task in PowerShell, run as an administrator. This is the form you can keep in source control and run again on the next server.
$action = New-ScheduledTaskAction -Execute 'powershell.exe' `
-Argument '-NoProfile -NonInteractive -ExecutionPolicy Bypass -File "C:\Scripts\Send-SalesFile.ps1"' `
-WorkingDirectory 'C:\Scripts'
$trigger = New-ScheduledTaskTrigger -Daily -At 2:30am
$settings = New-ScheduledTaskSettingsSet `
-StartWhenAvailable `
-ExecutionTimeLimit (New-TimeSpan -Hours 1) `
-MultipleInstances IgnoreNew
$cred = Get-Credential -Message 'The account the task runs as, DOMAIN\name'
Register-ScheduledTask -TaskName 'Send sales file' -TaskPath '\Retail\' `
-Action $action -Trigger $trigger -Settings $settings `
-User $cred.UserName -Password $cred.GetNetworkCredential().PasswordWhat each piece does, from the ScheduledTasks reference:
-StartWhenAvailablelets the task start "at any time after its scheduled time has passed", so a server that was off at 02:30 runs it when it comes back.-ExecutionTimeLimitmarks the run as failed if it has not finished in an hour. Without it, the default limit is three days.-MultipleInstances IgnoreNewignores a new run while the last one is still going.-TaskPathmust start and end with\.-Forcereplaces a task of the same name.
To run it now and read the result:
Start-ScheduledTask -TaskName 'Send sales file' -TaskPath '\Retail\'
Start-Sleep -Seconds 30
Get-ScheduledTaskInfo -TaskName 'Send sales file' -TaskPath '\Retail\' |
Select-Object LastRunTime, LastTaskResult, NextRunTime, NumberOfMissedRuns#What Last Run Result 0x1 means
Last Run Result shows what the task's program returned, in hexadecimal. Here the program is powershell.exe, so the number is the script's exit code. Under -File, Microsoft's page says a successful run returns 0, exit with a number returns that number, and "when a script-terminating error occurs, the exit code is set to 1". So 0x1 is PowerShell saying the script stopped on an error. Task Scheduler is not the problem.
The usual reasons a script that works by hand ends with 1 as a task:
- A path that depends on where you were.
.\file.csvnow meansC:\Windows\System32\file.csv. Set Start in, or build paths from$PSScriptRoot. - The account. The task's account cannot read the folder or write to the share, or Do not store password is ticked and the share is on another machine.
- A prompt. With
-NonInteractive, anything that asks a question fails at once. - A module that loads from your profile.
-NoProfilemeans it is not there. Import it in the script.
The transcript from step 1 holds the actual error. Other codes you will meet, from Microsoft's Task Scheduler error and success constants:
| Last Run Result | Microsoft's meaning |
|---|---|
0x0 | The script ended with exit code 0 |
0x41301 | "The task is currently running." |
0x41303 | "The task has not yet run." |
0x41306 | "The last run of the task was terminated by the user." |
0x8004131F | "An instance of this task is already running." |
#The task's history
Each task has a History tab, and Microsoft's troubleshooting page sends you there first: it shows whether the task was triggered and whether it completed. The events themselves are in Event Viewer › Applications and Services Logs › Microsoft › Windows › TaskScheduler › Operational. If the tab is empty, check that the log is on, and turn it on if not, with wevtutil:
wevtutil gl Microsoft-Windows-TaskScheduler/Operational
wevtutil sl Microsoft-Windows-TaskScheduler/Operational /e:trueThe last week's completed actions for the task, newest first:
Get-WinEvent -FilterHashtable @{
LogName = 'Microsoft-Windows-TaskScheduler/Operational'
Id = 201
StartTime = (Get-Date).AddDays(-7)
} | Where-Object { $_.Message -like '*\Retail\Send sales file*' } |
Select-Object TimeCreated, Message#Two ways to be told it failed
Task Scheduler's own Send an e-mail action is gone: Microsoft's reference for it says "This object is no longer supported", with support ending at Windows 7 and Windows Server 2008 R2. Its suggested workaround is Send-MailMessage, which its own page now calls obsolete because it "doesn't guarantee secure connections to SMTP servers". On Exchange Online, Microsoft points to Send-MgUserMail instead. The examples below use Send-MailMessage with an internal relay, because it is still what ships in Windows PowerShell 5.1: swap in your own sender.
1. The script reports its own failure. In step 1's catch block, after $code = 1, add:
Send-MailMessage -SmtpServer 'relay.example.local' `
-From 'store-jobs@example.com' -To 'it-alerts@example.com' `
-Subject "${env:COMPUTERNAME}: sales file not sent" `
-Body $_.Exception.MessageIt catches every failure the script sees. It cannot catch a night the script never started.
2. A watcher task that reads the others. Save this as C:\Scripts\Watch-Tasks.ps1 and schedule it at 06:00 the same way as in step 3. It looks at every task in \Retail\ and complains about any that failed, or whose last run is more than 26 hours old.
# C:\Scripts\Watch-Tasks.ps1
$late = (Get-Date).AddHours(-26)
$bad = Get-ScheduledTask -TaskPath '\Retail\' |
Where-Object { $_.State -ne 'Disabled' } |
Get-ScheduledTaskInfo |
Where-Object { $_.LastTaskResult -ne 0 -or $_.LastRunTime -lt $late } |
Select-Object TaskName, LastRunTime,
@{ n = 'Result'; e = { '0x{0:X}' -f $_.LastTaskResult } }
if ($bad) {
Send-MailMessage -SmtpServer 'relay.example.local' `
-From 'store-jobs@example.com' -To 'it-alerts@example.com' `
-Subject "${env:COMPUTERNAME}: $(@($bad).Count) scheduled task(s) need a look" `
-Body ($bad | Format-Table -AutoSize | Out-String)
exit 1
}
exit 0The watcher also catches the task that never ran: the server was off and came back late, the password expired, someone disabled the trigger. Between them, the two cover the cases Task Scheduler leaves to you.
#One morning at five stores, worked through
An invented chain of 120 stores runs Send sales file on every store server at 02:30. Here is what the watcher saw on one morning for five of them, and what was true in the ERP.
| Store | Last Run Result | What the watcher said | What was true in the ERP |
|---|---|---|---|
| ST-004 | 0x0 | Nothing | Agreed with the tills |
| ST-011 | 0x1 | Failed: "No sales file for 20261127" | Nothing for the day; the POS export had not run |
| ST-014 | 0x0 | Nothing | 11,920.00 against 12,400.00 at the tills, 480 apart |
| ST-022 | 0x41303 | Last run older than 26 hours | 6,410.75 missing: a new server, the task never ran |
| ST-031 | 0x0 | Nothing | 8,119.96 against 8,120.00, 0.04 of rounding |
Invented figures. Task Scheduler, the script and the watcher did their jobs: ST-011 and ST-022 were reported before anyone opened a spreadsheet. ST-014 is the one that got through. Its task succeeded, the file arrived, and the ERP still booked the day 480 short. Exit code 0 says the script finished. It does not say two systems agree. ST-031 needed nothing, and a rule that ignores 0.04 is the only thing that keeps it out of the inbox.
#Where Task Scheduler runs out
You now have a script on a schedule that says when it failed, without Mosaic. For one server, that is the job done. At 120 store servers, two things are left. Register-ScheduledTask and Get-ScheduledTaskInfo both take -CimSession, so you can install and read the task on every server from one script. Somebody still has to read 120 answers each morning, and none of them says whether the ERP took the right numbers. The back-office reconciliation post lists what to check every night.
DataMosaic does those two parts. A check reads the tills and the ERP, lines their rows up on store and business date, and shows each store as matched, differing or missing. Rules decide whether a run passed, so ST-031's 0.04 does not fail it. On a differing row such as ST-014, an investigation works through the reasons the ERP can miss or refuse data. A check only reads. Mosaic changes a system only through a workflow you build, started by a check, a schedule, a call or by hand. On a Mosaic installed on Windows inside your network, a workflow's Run on another machine node can run a script such as Get-ScheduledTaskInfo on each store's server through PowerShell remoting, and a monitor shows the last answer as one row per store, red where a task failed. Mosaic's manual calls that node new, so try it on one server first. Mosaic is not a scheduler: keep Task Scheduler for the jobs on each server. If you are weighing other tools for jobs between systems, see the Power Automate alternatives post.
#Questions people ask
#What does 0x1 mean in Task Scheduler for a PowerShell script?
It is exit code 1 from powershell.exe. With -File, PowerShell returns 1 when a script-terminating error stops the script, or when the script runs exit 1. The script's transcript or log holds the real error.
#What do I put in Program/script and Add arguments to run a .ps1 file?
Program/script is powershell.exe. Add arguments (optional) is -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "C:\Scripts\YourScript.ps1", with -File and the path last, and Start in (optional) the script's folder.
#Why does my script work by hand but not as a scheduled task?
Usually the working directory, which is %windir%\system32 without Start in, or the account: it cannot reach a share, or Do not store password is ticked, which limits the task to local resources. A prompt under -NonInteractive fails at once.
#How do I see when a scheduled task last ran with PowerShell?
Run Get-ScheduledTaskInfo -TaskName 'Name' -TaskPath '\Folder\'. It returns LastRunTime, LastTaskResult, NextRunTime and NumberOfMissedRuns. Pipe Get-ScheduledTask -TaskPath '\Folder\' into it to see every task in a folder.
#Can Task Scheduler email me when a task fails?
Not any more. Microsoft says its Send an e-mail action is no longer supported. Have the script send the message itself, or schedule a second task that reads Get-ScheduledTaskInfo and mails when a result is not 0.