I'm trying to run multiple backup scripts for my external hard drives, with attended and unattended versions. The attended ones handle tasks normally, while the unattended ones set the power profile to high performance to prevent my PC from sleeping and hibernate it once the job is done. However, if I run several scripts overnight, I don't want the hibernation to kick in prematurely when some scripts are still working.
I'm looking for a way to check if any other PowerShell instances are still active before initiating hibernation. I want to add some code to my unattended script to handle this. Can anyone provide a code example showing how I can check for running PowerShell scripts so that I can delay the hibernation until they're all finished? As I'm new to PowerShell, I would appreciate a literal code example, not just instructions on what to do.
4 Answers
You can check for running PowerShell processes using this command: `Get-Process PowerShell`. From there, look at the `Commandline` property of each process to find the specific instance you need to monitor. This method can help you identify if your scripts are still running before deciding to hibernate your PC.
How would I inspect the `Commandline` property? I'm not sure how to do that in PowerShell.
Instead of manual backups, why not schedule them? It could streamline your process and eliminate the risk of overlapping runs.
You can periodically check for running PowerShell processes with this loop:
`Do {Start-Sleep -Seconds 15} Until ((Get-Process -Name PowerShell -ErrorAction Ignore) -eq $null)` This will keep checking until no PowerShell processes are found. If you want to be more specific, you can enhance it using the command line checks.
Consider using a mutex for better synchronization. When your backup script starts, it can request a mutex lock, and release it once it's done. Your hibernation script can then check for this lock and only hibernate when it's free.
You could also assign the process result to a variable for easier management.