我一直试图从VBA运行Powershell脚本,但是没有成功。 这个想法是在VBA内编写Powershell-coe(以使某些过程自动化)。 为了简化,下面有一些尝试。
在VBA上
Sub test()
Dim command_shell As Variant
Dim code As String
code = "PowerShell -Command ""{import-csv c:\Users\flyer\Documents\H2SO4.csv -delimiter ';' | select -first 3}"""
command_shell = Shell(code, vbNormalFocus)
Debug.Print code
End Sub
或者
Sub test()
Dim command_shell As Variant
Dim code As String
code = "import-csv c:\Users\flyer\Documents\H2SO4.csv -delimiter ';' | select -first 3"
command_shell = Shell(code, vbNormalFocus)
Debug.Print code
End Sub
但是很遗憾,没有任何运行,而且我看不到PowerShell屏幕。
要仔细检查代码是否未运行,我尝试使用该命令来发布脚本:
code = "PowerShell -Command {Start-Transcript}"
在这种情况下,PowerShell会很快出现并消失,但不会生成任何脚本文件。
您有更好的主意来解决这个问题吗?
答案 0 :(得分:2)
由于您是从命令提示符处有效运行此命令的,因此需要&,因为cmd无法识别脚本块。
code = "PowerShell -Command """& {import-csv c:\Users\flyer\Documents\H2SO4.csv -delimiter ';' | select -first 3}"""
这是powershell.exe中的适用部分/?
-Command
Executes the specified commands (and any parameters) as though they were
typed at the Windows PowerShell command prompt, and then exits, unless
NoExit is specified. The value of Command can be "-", a string. or a
script block.
If the value of Command is "-", the command text is read from standard
input.
If the value of Command is a script block, the script block must be enclosed
in braces ({}). You can specify a script block only when running PowerShell.exe
in Windows PowerShell. The results of the script block are returned to the
parent shell as deserialized XML objects, not live objects.
If the value of Command is a string, Command must be the last parameter
in the command , because any characters typed after the command are
interpreted as the command arguments.
To write a string that runs a Windows PowerShell command, use the format:
"& {<command>}"
where the quotation marks indicate a string and the invoke operator (&)
causes the command to be executed.