从wscript.exe进程获取脚本名称

时间:2013-02-28 00:49:32

标签: vbscript

我正在使用此代码:

Dim name
name = CreateObject("WScript.Shell").ExpandEnvironmentStrings("%computername%")
Set wmi = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" _ 
    & name & "\root\cimv2")
For Each hwnd In wmi.InstancesOf("Win32_Process")
    If hwnd.Name = "wscript.exe" Then
        'get name and possibly location of currently running script
    End If
Next

我已成功列出所有流程并选择wscript.exe。但是,我搜索过并找不到找到wscript.exe中运行的脚本名称的方法,即。它是myscript.vbs还是jscript.js还是其他什么。如果有办法找到脚本的整个路径,可以获得奖励。

修改

通过更多搜索,我找到了解决方案。在上面的脚本中,hwnd变量存储wscript.exe进程的句柄。句柄属性为hwnd.CommandLine。它显示了如何从命令行调用它,因此它将类似于:

"C:\Windows\System32\wscript.exe" "C:\path\to\script.vbs"

所以我可以解析hwnd.CommandLine字符串来查找所有正在运行的脚本的路径和名称。

2 个答案:

答案 0 :(得分:10)

您拥有ScriptNameScriptFullName属性。

' in VBScript
WScript.Echo WScript.ScriptName
WScript.Echo WScript.ScriptFullName

// in JScript
WScript.Echo(WScript.ScriptName);
WScript.Echo(WScript.ScriptFullName);

[编辑]在这里(使用.CommandLine属性):

Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" _
    & "." & "\root\cimv2")

Set colProcesses = objWMIService.ExecQuery( _
    "Select * from Win32_Process " _
    & "Where Name = 'WScript.exe'", , 48)

Dim strReport
For Each objProcess in colProcesses
    ' skip current script, and display the rest
    If InStr (objProcess.CommandLine, WScript.ScriptName) = 0 Then
        strReport = strReport & vbNewLine & vbNewLine & _
            "ProcessId: " & objProcess.ProcessId & vbNewLine & _
            "ParentProcessId: " & objProcess.ParentProcessId & _
            vbNewLine & "CommandLine: " & objProcess.CommandLine & _
            vbNewLine & "Caption: " & objProcess.Caption & _
            vbNewLine & "ExecutablePath: " & objProcess.ExecutablePath
    End If
Next
WScript.Echo strReport

答案 1 :(得分:0)

myProcess="wscript.exe"               
Set Processes = GetObject("winmgmts:").InstancesOf("Win32_Process")
For Each Process In Processes
 If StrComp(Process.Name, myProcess, vbTextCompare) = 0 Then     'check if process exist      
   CmdLine=process.commandline                  
 End If
Next
myArr=split(CmdLine,"\")
mySN=replace(myArr(ubound(myArr)),"""","")
Wscript.Echo "Full Pth: " & Cmdline &vbcrlf&"Script Name: "& mySN