我正在使用以下代码获取当前启动的wsf脚本的当前pid:
<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>
当我按顺序启动wsf脚本时,它工作得很好,但是当更多的脚本“并行”启动时会出现意外情况,多个脚本会获得相同的进程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
更不用说随机我将一些garbe作为例外。
我的问题如下:
Windows如何为同时启动的进程获取相同的进程ID?
导致例外的原因是什么?
我对wsf没有经验,上面的代码实际上是一个复制粘贴,我做错了吗?