如何从excel vba作为多行运行多行Powershell脚本? [英] How do I run a multi-line powershell script from excel vba as a single line?

查看:53
本文介绍了如何从excel vba作为多行运行多行Powershell脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Powershell:

Powershell:

line1
line2
line3
line4

Excel VBA:

Excel VBA:

Set objShell = CreateObject("Wscript.Shell")
objShell.Run ("C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoExit -executionpolicy bypass -command ""line1; line2; lin3; line4"")

line1 将运行并打开Powershell窗口,但其余命令将不运行.我可以分别将 line2 line3 line4 分别复制并粘贴到powershell窗口中,然后它们将分别运行.

line1 will run and open a powershell window but the rest of the commands do not run. I can copy and paste each of line2, line3 and line4 individually into the powershell window at the prompt and they will each run.

推荐答案

我建议使用powershell的 -EncodedCommand 参数.

I suggest using powershell's -EncodedCommand parameter.

从他们的帮助文档中( powershell-?):

From their help documentation (powershell -?):

# To use the -EncodedCommand parameter:
$command = 'dir "c:\program files" '
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)
powershell.exe -encodedCommand $encodedCommand

要为参数生成base64(缩短):

To generate the base64 for the parameter (shortened):

[System.Convert]::ToBase64String(
    [System.Text.Encoding]::Unicode.GetBytes(@'
line1
line2
line3
line4
'@)
)

实际情况:

powershell -NoExit -NoLogo -NoProfile -ExecutionPolicy Bypass -EncodedCommand "bABpAG4AZQAxAA0ACgBsAGkAbgBlADIADQAKAGwAaQBuAGUAMwANAAoAbABpAG4AZQA0AA=="

注意:这将失败,因为无法识别'line1',因为我是从字面上理解您的示例的.

Note: This will fail with 'line1' is not recognized since I took your example literally.

这篇关于如何从excel vba作为多行运行多行Powershell脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆