如何从vbscript将进程名参数传递给powershell

时间:2015-03-25 12:13:28

标签: powershell vbscript parameters

如果已创建一个VBS脚本,该脚本会监视新创建的进程,如notepad.exe或calc.exe。当发现新的记事本或计算过程时,我喜欢使用找到的进程名在powershell中执行某些操作。

当我手动编辑VBS文件中的进程名时,我创建的VBS脚本工作正常,但是当我尝试使用/传递进程名形式vbs(strName)到powershell时,我希望看到进程名(notepad.exe),但是,PowerShell窗口显示" strName"。

我已经在互联网上找到了一个没有结果的解决方案。


我的VBS文件[start.vbs]

来源:http://blogs.technet.com/b/heyscriptingguy/archive/2009/11/02/hey-scripting-guy-november-1-2009.aspx

arrProcesses = Array("calc.exe","notepad.exe")
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
i = 0

Set colMonitoredProcesses = objWMIService. ExecNotificationQuery _        
("Select * From __InstanceCreationEvent Within 5 Where TargetInstance ISA 'Win32_Process'")

Do While i = 0
Set objLatestProcess = colMonitoredProcesses.NextEvent
strProcess = LCase(objLatestProcess.TargetInstance.Name)
For Each strName in arrProcesses
    If strName = strProcess Then


''Run Powershell file
'source: https://stackoverflow.com/questions/19156178/passing-arguments-to-powershell

Set WshShell = CreateObject("WScript.Shell")

''this works great
WshShell.Run ("Powershell.exe -file .\GetParamFromVBS.ps1 ""notepad.exe"" ")

'this doesnt
WshShell.Run ("Powershell.exe -file .\GetParamFromVBS.ps1 ""strName"" ")

'OR
'Trying to work arround it, with no result :(
RUNPSVAR="(" + """" +"Powershell.exe -file .\GetParamFromVBS.ps1 & """"" +strName +"""""" +""& " " +"""" +")"
wscript.Echo RUNPSVAR

WshShell.Run ("Powershell.exe -file .\GetParamFromVBS.ps1 ""RUNPSVAR"" ")

    End If
Next
Loop

我的Powershell文件[GetParamFromVBS.ps1]

来源:How to pass command-line arguments to a PowerShell ps1 file

param($p1, $p2, $p3, $p4)
$Script:args=""

write-host "Num Args: " $PSBoundParameters.Keys.Count

foreach ($key in $PSBoundParameters.keys) {
$Script:args+= "`$$key=" + $PSBoundParameters["$key"] + "  "
}
write-host $Script:args

pause

任何想法?

2 个答案:

答案 0 :(得分:2)

变化:

WshShell.Run("Powershell.exe -file .\GetParamFromVBS.ps1 ""strName"" ")

要:

WshShell.Run("Powershell.exe -file .\GetParamFromVBS.ps1 '" & strName & "'")

答案 1 :(得分:0)

变量不是字符串文字。

这样的事情

a = "a string literal" & aVariableContainingAString