Reputation: 21
I'm new to powershell and while practicing the examples for loops, I came across a problem that I couldn't solve.
I want to call a notification about the status of a process running in the system through a loop However, in the code, only the alarm of the process executed first among Taskmgr or Calculator is called by Wait-Process.
I mean, Wait-Process by Sequential Execution makes notification invocation by loop no longer possible
below is my code
do{
Start-Sleep -s 3
$Calculator = Get-Process -Name 'Calculator'
$Taskmgr = Get-Process -Name 'Taskmgr'
if ($Calculator)
{
Show-Notification -ToastTitle 'Calculator is open.'
Wait-Process -name 'Calculator'
Show-Notification -ToastTitle 'Calculator is closed.'
}
if ($Taskmgr)
{
Show-Notification -ToastTitle 'Taskmgr is open.'
Wait-Process -name 'Taskmgr'
Show-Notification -ToastTitle 'Taskmgr is closed.'
}
} while (1 -eq 1)
Since I am Japanese, I am not familiar with English, so I am using a translator. thank you.
I'm still not good enough skill to recreate the code. sorry
Upvotes: 2
Views: 206
Reputation: 59781
Wait-Process
blocks the thread indefinitely without the -Timeout
parameter but also, while using this parameter if it times out you would get an error and the cmdlet is not particularly useful for this use case.
You could achieve this by using only Get-Process
with -ErrorAction SilentlyContinue
to avoid errors when the processes are not running and adding else
conditions:
while ($true) {
Start-Sleep -s 3
$calc = Get-Process -Name CalculatorApp -ErrorAction SilentlyContinue
$taskmgr = Get-Process -Name Taskmgr -ErrorAction SilentlyContinue
# if calc is running
if ($calc) {
# and there was no notification before
if (-not $calcOpen) {
# display notification
'Calculator is opened.'
# and set a reminder to not display more popups
$calcOpen = $true
}
}
# if calc was not running
else {
# and was running before
if ($calcOpen) {
# display notification
'Calculator is closed.'
# and set a reminder that calc has been closed
$calcOpen = $false
}
}
# same logic applies here
if ($taskmgr) {
if (-not $taskmgrOpen) {
'Taskmgr is opened.'
$taskmgrOpen = $true
}
}
else {
if ($taskmgrOpen) {
'Taskmgr is closed.'
$taskmgrOpen = $false
}
}
}
Upvotes: 2