网友JPBlanc等人针对此类问题给出了很好的解决方案:
Set Args = Wscript.Arguments
'MsgBox "Chemin LDAP: " & Args(0)
'MsgBox "Classe: " & Args(1)
Set objShell = CreateObject("Wscript.Shell")
objShell.Run "c:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -nologo -Noninteractive -file c:\SlxRH\RhModif.ps1 " & chr(34) & Args(0) & chr(34) , 0
我已经测试了这样的解决方案,它工作正常。但是,我的问题涉及当标识为“-file”选项参数的文件路径中有空格时的情况;例如,如果上面的代码示例的文件路径为:
c:\Slx RH\RhModif.PS1
观察文件路径中的空白。问题是:如何正确转义文件路径。我还没有找到一种方法来做到这一点(让它发挥作用)。
我在这个站点和一般的“interweb”上进行了搜索,并且了解到(我认为)存在两个级别的脚本解释:VBscript 和 Wscript。另一个很好的例子出现在这里(链接到带有这个标题的完整页面):
Run scheduled tasks with WinForm GUI in PowerShell
Dim objShell
Set objShell=CreateObject("WScript.Shell")
strExpression="get-date | add-content c:\temp\test.txt"
strCMD="powershell -sta -noProfile -NonInteractive -nologo -command " & Chr(34) & "&{" & strExpression &"}" & Chr(34)
objShell.Run strCMD,0
我已经测试过了,它对我有用。虽然没有使用“-file”选项,但此示例给出(您的想法)将是为 strCMD 变量放置“-command”或“-file”输入的通用方法。但是,当我使用以下代码时,它不起作用:
Dim objShell
Set objShell=CreateObject("WScript.Shell")
strExpression="C:\aP_RDB\Set Up\SimpleInsert.PS1"
strCMD="powershell -noprofile -executionpolicy Unrestricted -NonInteractive -file " & Chr(34) & "&{" & strExpression &"}" & Chr(34)
objShell.Run strCMD,0
在我上面的例子中,我基本上复制了上面的代码引用(以及从列出的链接),用我的文件路径(包括空格)替换变量 strExpression 的 PS 命令,并通过替换“-command”参数与“-file”参数。但是,错误消息指向无法识别的参数“c:\aP_RDB\Set”,也就是说,它看不到整个路径“C:\aP_RDB\Set Up\SimpleInsert.PS1”。似乎引号(或其他东西)的转义不起作用......更好地说,我没有正确地做。
任何深思熟虑的建议将不胜感激。仅供引用:我已经在 Powershell 中尝试了 -WindowStyle Hidden 选项;我喜欢许多人发现这不是跨 Windows 平台的一致方法(更具体地说对我来说:我无法让它工作)。
最佳答案
感谢您的引用,这里有两种启动名称中包含空格的脚本的方法:
1)使用双“(”)
set Args = Wscript.Arguments
MsgBox "Chemin LDAP: " & Args(0)
'MsgBox "Classe: " & Args(1)
Set objShell = CreateObject("Wscript.Shell")
objShell.Run "c:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -nologo -Noninteractive -file ""c:\temp\test arg.ps1"" " & chr(34) & Args(0) & chr(34) , 0
2) 按照我在本文末尾的解释 ""PowerShell.exe" ne sait pas démarrer sans afficher une fenêtre" 编写自己的没有控制台的 PowerShell.exe。 (对不起,法语)
关于powershell - 使用 VBscript 隐藏 Powershell 窗口 : whitespace in the -file filepath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14016488/