Hello everybody,
A machine has difficulties to work during the Windows updates. It seems there are a few errors in the drivers paths, and the updates above this finish by making much.
So, I should say that consulting the bank account can wait that the process tiworker has finished working.
Get-Process TiWorker
returns the TiWorker process, when it is opened, but once it has finished, it raises an exception.
What is the most elegant way to detect whether TiWorker is working, and to return true or false, rather than an exception?
Maybe not elegant, but short for sure:
[boolean](Get-Process -Name TiWorker -ErrorAction SilentlyContinue)
Place your execution inside a grouping expression, ( ), and then cast that result as a [Boolean]. Use the built-in ErrorAction to suppress the error text and you get a True if it returned something, or a False if it didn’t.
Thank you for your quick answer.
I had the idea of the try…catch, well if it is only one it will do it.
And TiWorker has worked just a little while when your answer arrived, which allowed me to verify the syntax.
Now I am going to practice gymnastics with Read-Host and Write-Host, to allow the user to abandon, or wait until the end otherwise.
Thanks
(I now have to remember where to click, to say it is answered.)
I presume that with TiWorker there will be no problem, but in a general case, you have to pay attention that you can have several processes with the same name, in which case the type of the return data is not the same.
You have three possibilities:
- if no process of the said name is opened, you obtain null
- if there is one process, you obtain the process
- if there is more than one process, you obtain a list of processes (array of processes, perhaps?)
In the three cases the Count property exists. I made the tests with Notepad2:
Function ExistProc
{
param (
[string[]]$ProcName
)
$t = (Get-Process -Name $ProcName -ErrorAction SilentlyContinue)
$b = ($t.Count -gt 0);
return $b;
}
Write-Host "Beginning"
if(ExistProc("Notepad2"))
{
Write-Host "Notepad2 is opened"
while(ExistProc("Notepad2"))
{
Start-Sleep 5; Write-Host -NoNewLine "*";
}
Write-Host "";
Write-Host "End of updates.";
}
Oh, did not pay attention that I gave a list (array) of chains in input, I presume a chain could be very well as well.
The following of the script is executed 5 seconds after the last process if finished.
The display of “*” can be interrupted by Ctrl C, at the end I should verify whether the process still exists
if(ExistProc("Notepad2"))
in which case return a different code and avoid the execution of the following.