Forum Discussion
Externally trigger a .ps1 to exit
- Feb 09, 2022taking action within the script when an external action has stopped the scheduled job - no, this isnt possible.
Thanks for the quick response. Here's more detail.
I have a script in a .ps1 file. I run PowerShell.exe from a scheduled task and provide the .ps1 as a PowerShell command-line argument. The script is moving files with Get-ChildItem | ForEach-Object and may run for days. The script generates status messages via Write-Output. When the script has moved all the files, it provides a final message with stats and exits. If we need to stop the script before all files are moved, we lose the final statistics. I considered a "brute force" semaphore such as creating a file that the script checks for that signals it to shut down. Is there a more elegant solution? Environment variable? Some other sort of system trigger?
I'm not married to running the script from the Task Scheduler. (I just need the script to run without a logged-in session.)
Thanks in advance for you help.
OK, some thoughts:
- You say the script 'may run for days' is this because there are lots of files or they are large files or you have slow network ... etc? Can you set the job to run for a fixed length of time and just trigger it more frequently? This way you know it will more often stop gracefully?
- You are using Write-Output to add updates to the session as (i assume) files are moved. Why not switch this to writing your progress to a static file with Add-Content?
$Date = "{0:yyyymmdd_HHmm}" -f (Get-Date)
$Logfile = "[MySecurePathLocation]\FileMoverJob\$Date`_Process.txt"
$Logfile
$Msg = "{0:yyyymmdd_HHmmss}`tProcess starting." -f (Get-Date)
$Msg | add-Content $Logfile
#[getchilditem loop I assume]
$Msg = "{0:yyyymmdd_HHmmss}`tMoving $ThisFile." -f (Get-Date)
$Msg | add-Content $Logfile
##end of loop
$Msg = "{0:yyyymmdd_HHmmss}`tProcess complete." -f (Get-Date)
$Msg | add-Content $Logfile
This way if the process stops unexpectedly you will have a file with a log of what has been completed and the times it occurred...
- Mark_BlockFeb 09, 2022Copper ContributorIt seems I'm explaining this badly. I'm not losing the output written by Write-Output. Also, running the script more frequently won't solve the problem. The problem is that the script doesn't know it's being shut down. (BTW, I solved the problem using an external semaphore file that the script checks but I'm still wondering if there's a more "elegant"). I'll try to explain again.
When the script is shut down by an external action, like hitting End from Task Scheduler, the script has no idea it's being shut down. I need a method that allows the script, from inside the script, to know it's being shut down.- Jonathan_AllenFeb 09, 2022Brass Contributortaking action within the script when an external action has stopped the scheduled job - no, this isnt possible.
- Mark_BlockFeb 09, 2022Copper ContributorOK. That was my conclusion as well. Thanks for your help.