How do I run a multi-line powershell script from e

2019-08-16 11:01发布

Powershell:

line1
line2
line3
line4

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 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.

1条回答
啃猪蹄的小仙女
2楼-- · 2019-08-16 11:23

I suggest using powershell's -EncodedCommand parameter.

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

To generate the base64 for the parameter (shortened):

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

In action:

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

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

查看更多
登录 后发表回答