2013-11-20 58 views
0

我需要製作一個簡單的vbs腳本來自動運行某個進程。我在微軟的網站上找到了以下腳本。它運行正常,以原始示例顯示的方式運行notepad.exe,但我試圖修改它以運行myprog.exe。這個程序的完整路徑是:C:\myprogdir\myprog.exe在VBS中啓動進程:path not found

Const SW_NORMAL = 1 
strComputer = "." 
strCommand = "myprog.exe" 
strPath = "C:\myprogdir\" 

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

' Configure the Notepad process to show a window 
Set objStartup = objWMIService.Get("Win32_ProcessStartup") 
Set objConfig = objStartup.SpawnInstance_ 
objConfig.ShowWindow = SW_NORMAL 

' Create Notepad process 
Set objProcess = objWMIService.Get("Win32_Process") 
intReturn = objProcess.Create _ 
    (strCommand, strPath, objConfig, intProcessID) 
If intReturn <> 0 Then 
    Wscript.Echo "Process could not be created." & _ 
     vbNewLine & "Command line: " & strCommand & _ 
     vbNewLine & "Return value: " & intReturn 
Else 
    Wscript.Echo "Process created." & _ 
     vbNewLine & "Command line: " & strCommand & _ 
     vbNewLine & "Process ID: " & intProcessID 
End If 

我不斷收到返回值:9,這表明「找不到路徑」。但路徑是正確的。有沒有我沒有得到的東西?

+0

一見鍾情,我認爲配置不對。 –

+0

@DavidCandy:更簡單的一行:'CreateObject(「WScript.Shell」)。運行「C:\ myprogdir \ myprog.exe」 – Helen

回答

1

你不需要所有的東西來啓動一個進程,你只需要Shell對象。此外,請確保將可執行文件的路徑包含在引號中(以防路徑中有空格)。就像這樣:

Option Explicit 

Dim shl 

Set shl = CreateObject("Wscript.Shell") 
Call shl.Run("""C:\myprogdir\myprog.exe""") 
Set shl = Nothing 

WScript.Quit 
0

除非被包含在系統的%PATH%環境變量,你的程序的路徑,你需要使用的完整路徑可執行文件指定命令行。像工作目錄一樣指定路徑將不起作用。

strProgram = "myprog.exe" 
strPath = "C:\myprogdir" 

Set fso = CreateObject("Scripting.FileSystemObject") 
strCommand = fso.BuildPath(strPath, strProgram) 

... 

intReturn = objProcess.Create(strCommand, strPath, objConfig, intProcessID) 

使用BuildPath方法將節省您造成頭痛具有跟蹤前導/尾隨反斜槓。

請注意,您需要在包含空格的路徑周圍放置雙引號,例如像這樣:

strCommand = Chr(34) & fso.BuildPath(strPath, strProgram) & Chr(34) 

正如其他人已經指出的那樣,有更簡單的方法可以在本地計算機上啓動一個過程,就像Run

Set sh = CreateObject("WScript.Shell") 
sh.Run strCommand, 1, True 

ShellExecute

Set app = CreateObject("Shell.Application") 
app.ShellExecute strCommand, , strPath, , 1 

雖然在RunShellExecute之間有一些顯着的差異。前者可以同步或異步運行(這意味着命令不會等待外部程序終止)。後者OTOH總是異步運行(即,方法立即返回而不等待外部程序終止),但具有的優點是,當UAC通過指定動詞"runas"作爲4 啓用UAC時,它可用於啓動具有提升權限的程序th的說法。

但是,這些方法只允許在本地計算機上啓動進程。如果你希望能夠發動遠程計算機上的進程,你將不得不使用WMI:

strComputer = "otherhost" 

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

有關WMI連接到遠程主機的更多信息,請here