简体   繁体   中英

How do I run a multi-line powershell script from excel vba as a single line?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM