I'm using the following code to obtain the current pid of the currently started wsf script:
<script language="VBScript" type="text/vbscript">
<![CDATA[
On Error Resume Next
Err.Clear
REM Obtain process id
WScript.Echo "#$% Find Process ID"
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Function CurrProcessId
Dim oShell, sCmd, oWMI, oChldPrcs, oCols, lOut
lOut = 0
Set oShell = CreateObject("WScript.Shell")
Set oWMI = GetObject(_
"winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Randomize
sCmd = "/K @echo " & Int(Rnd * 3333) * CDbl(Timer) \ 1
oShell.Run "%comspec% " & sCmd, 0
WScript.Sleep 100 'For healthier skin, get some sleep
Set oChldPrcs = oWMI.ExecQuery(_
"Select * From Win32_Process Where CommandLine Like '%" & sCmd & "'", ,32)
For Each oCols In oChldPrcs
lOut = oCols.ProcessId 'get parent
oCols.Terminate 'process terminated
Exit For
Next
Set oChldPrcs = Nothing
Set oWMI = Nothing
Set oShell = Nothing
CurrProcessId = lOut
End Function
WScript.Echo CurrProcessId
WScript.Echo "#$% Process ID Found"
if Err.Number <> 0 then
' An exception occurred
WScript.Echo "Exception:" & vbCrLf &_
" Error number: " & Err.Number & vbCrLf &_
" Error description: '" & Err.Description & vbCrLf
end if
]]>
</script>
It worked perfectly while I started the wsf scripts sequentially, however when more of them is started "parallelly" something unexpected happends, multiple scripts are obtaining the same Process ID:
10 scripts started
#$% Find Process ID
#$% Find Process ID
#$% Find Process ID
#$% Find Process ID
#$% Find Process ID
#$% Find Process ID
#$% Find Process ID
#$% Find Process ID
#$% Find Process ID
#$% Find Process ID
1472
#$% Process ID Found
6664
#$% Process ID Found
6456
#$% Process ID Found
6456
#$% Process ID Found
test1.wsf exit code 0
test10.wsf exit code 0
test2.wsf exit code 0
test4.wsf exit code 0
6456
#$% Process ID Found
4100
#$% Process ID Found
4100
#$% Process ID Found
4100
#$% Process ID Found
test3.wsf exit code 0
test5.wsf exit code 0
test6.wsf exit code 0
test7.wsf exit code 0
#$% Process ID Found
Exception:
Error number: -2147217406
Error description: 'Not found
6540
#$% Process ID Found
test8.wsf exit code 0
test9.wsf exit code 0
Not to mention that randomly I'm getting some garbe as exception.
My questions are the following:
How it's possible the Windows obtains the same process id for simultaneously started processes?
What causes the exception?
I'm not experienced in wsf and the above code is literally a copy paste, am I doing something wrong?