如何使用VBScript调用带有参数的PowerShell文件

时间:2019-01-03 10:04:54

标签: powershell vbscript system-tray

问候大家,新年快乐。

两天前我刚刚了解了PowerShell,它显示了。我试图制作自定义的气球提示,但没有为每个可能的事件制作单独的ps1脚本。我需要的是带有参数的ps1。

我在此站点上找到了这段代码: GitHub Invoke-BalloonTip

我通过以下方式成功地从PS窗口调用了它:

 . .\Invoke-BalloonTip.ps1
Invoke-BalloonTip -Message 'Message' -Title 'Title' -MessageType Info

但是,我需要从VBScript调用它。我尝试过:

Set objShell = CreateObject("Wscript.shell")
objShell.run("powershell -command . c:\PowerShellTest\Invoke-BalloonTip.ps1" & Invoke-BalloonTip -Message 'Invoked' -Title 'Invoked' -MessageType Info)

Set objShell = CreateObject("Wscript.shell")
objShell.run("powershell -command ""& { . c:\PowerShellTest\Invoke-BalloonTip.ps1; Invoke-BalloonTip -Message 'Message' -Title 'Title' MessageType Info }""")

还有一些结果不尽人意。这两个示例是PS窗口运行时唯一未显示任何错误的示例。对于这两个示例,PS窗口将短暂显示,并且不显示任何错误消息,但不显示气球提示。

我确定这是一个语法问题,但是我对它可能是什么一无所知。任何想法或建议都将受到欢迎和赞赏。

3 个答案:

答案 0 :(得分:1)

我认为问题出在原始Invoke-BalloonTip.ps1上,因为它试图在可用之前(通过加载System.Windows.Forms.ToolTipIcon)使用System.Windows.Forms类型。在命令中的较早位置添加它应该可以解决问题(尽管确实有点棘手):

Set objShell = CreateObject("Wscript.shell")
objShell.run("powershell.exe -command ""& {Add-Type -AssemblyName System.Windows.Forms;. C:\PowerShellTest\Invoke-BalloonTip.ps1; Invoke-BalloonTip -Message ""Message"" -Title ""Title"" -MessageType Info}""")

Invoke-BalloonTip.ps1PowerShell ISE中可以立即工作,因为默认情况下已正确加载了正确的程序集,但在powershell.exeVSCode中却不是这样。

答案 1 :(得分:0)

为了其他来这里遇到类似问题的人,如果您的消息或标题中有空格,这将不起作用。为了解决这个问题,我用单引号将字符串引起来:

objShell.run("powershell.exe -command ""& {Add-Type -AssemblyName System.Windows.Forms;. C:\PowerShellTest\Invoke-BalloonTip.ps1; Invoke-BalloonTip -Message ""'Message with Space'"" -Title ""'Title With Space:'"" -MessageType info}""")

答案 2 :(得分:0)

您可以使用此代码。

Dim strTitle, srtContext, strCommang

strTitle = "Title"
srtContext = "Text"

strCommang =    "powershell.exe -executionpolicy bypass -command " & _
                "[reflection.assembly]::loadwithpartialname('System.Windows.Forms')" & vbNewLine & _
                "[reflection.assembly]::loadwithpartialname('System.Drawing')" & vbNewLine & _
                "$notify = new-object system.windows.forms.notifyicon" & vbNewLine & _
                "$notify.icon = [System.Drawing.SystemIcons]::Information" & vbNewLine & _
                "$notify.visible = $true" & vbNewLine & _
                "$notify.showballoontip(10,'" & strTitle & "','" & srtContext & "',[system.windows.forms.tooltipicon]::None)"

Set objShell = CreateObject("Wscript.shell")
objShell.Run strCommang, 0
Set objShell = Nothing