Reputation: 1147
I'm getting a really frustrating error that sometimes comes up and sometimes it runs through without a problem. My code is:
function killProcesses(processes) { // A string array of process names.
for (i = 0; i < processes.length; i++) {
var process = Sys.WaitProcess(processes[i])
if (process.Exists) { // Sometimes the script will crash right here
process.Terminate()
}
}
Since I made the function I have always passed the exact same process names in, sometimes they are started others they aren't, that's never been a problem. But other times it will crash while running and tell me Object doesn't support this property or method
. Like I said, this function and the line that calls it have never been changed, so I don't understand why only sometimes it fails.
I've gotten this in other parts of my scripts before, so I wonder if it might be related or there's just something in general wrong with my system. What really baffles me is that Exists
should always exist on everything, so why is it sometimes just not there?
Upvotes: 2
Views: 386
Reputation: 5503
Maybe you could protect for null by having
If (process && process.Exists)
I would also loop down from the top just in case the process termination is affecting your process list.
Upvotes: 0
Reputation: 71
The Sys.WaitProcess(ProcessName)
method should either return the process found or an empty stub object with only property Exists
with a value false
if the process is not found. It doesn't matter if the process is found, it should be ok to use Exists
to check if the process is found.
I have the same problem with control objects as result value of the Find
method and it is widespread for all of the objects returned from the Find
method.
I have found a workaround:
If accessing a different property (e.g Name
) before accessing Exists
, there is no error.
obj.Name; // Add this to prevent error in obj.Exists below:
if (obs.Exists)
{
// Do something here
}
This only works if the objects are expected. In my case, they are. If the expected object is not found, obj.Name
will throw an error which is ok as expected.
In the case where the object may be expected not to be found, you would be stuck if Exists
does not work as the result value is not null or not empty and obj.Name
will throw an error which you want to avoid and the only condition you can check is obj.Exists
.
However, it may be worth trying to see if this works for process object if the process is found.
Upvotes: 2
Reputation: 3918
The problem with this code is that when you terminate the first process, indexes of the rest processes are reduced. This version of the code is better:
function killProcess(pName) {
var p = Sys.WaitProcess(pName, 5000, 1);
while (p.Exists) {
p.Terminate();
while (p.Exists)
Sys.Delay(50);
p = Sys.WaitProcess(pName, 5000, 1)
}
}
Upvotes: -1