I'm running a scheduled Windows task that calls a PowerShell script (script1.ps1). This script sets up some variables and then calls another script (script2.ps1). After script2 completes, I'm supposed to rename a log file and create a new one. However, I've noticed that even though script2 usually finishes without an issue, the task sometimes hangs, leading Windows to force it to terminate after 60 minutes. In script2, I log a message about its completion and then exit with a code, but it doesn't seem to transition back to script1 as expected. I'm unsure why this happens—has anyone experienced something similar, or can anyone suggest a solution?
4 Answers
It sounds like there's an issue in script2 that's causing it to hang. Even when you run script2 separately, if it still hangs, then the problem is likely within that script. Without seeing the code for script2, it's hard to pinpoint the issue. Can you share more about what script2 does?
Here's how I make sure my scheduled task captures exit codes properly when launching a second script. Try this:
```powershell
$SecondScript = Start-Process "powershell.exe" -ArgumentList "-WindowStyle Hidden -ExecutionPolicy Bypass -File `$PSScriptRootscript2.ps1`" -Wait -ErrorActionStop -PassThru
$SSExitCode = $SecondScript.ExitCode
[System.Environment]::Exit($SSExitCode)
```
This way, it'll wait for script2 to finish and correctly handle the exit code. Give it a shot!
So how are you confirming that script2 has finished? Are you just looking at the log output? Sometimes a PowerShell process can seem complete but is still running in the background. I think you might need to double-check the behavior of script2, as script1 will keep waiting for it to finish. Can you confirm it's not still running in the background?
From what I understand, PowerShell scripts use a method to handle exit codes, but if you're using `Exit` correctly, it should work. Just to clarify, does the script exit properly without the specific exit code logic? Maybe test it without the exit code handling to see if it resolves the issue.
I've used the exit in my other scripts without this issue, so it shouldn't be the problem.
The logs definitely show that script2 indicates it's complete right before it tries to exit.