Home > Mobile >  Run Script within Batch File with Parameters
Run Script within Batch File with Parameters

Time:09-23

I'm writing a Batch File, and in this batch file i execute a script.

Batch File:

PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""C:\Public\File\SomeScript.ps1""' -Verb RunAs}"

Now this works fine.

Is it possible to execute the SomeScript.ps1 with parameters ?

Like

@echo off
echo %1
echo %2
echo %3
echo %4
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""C:\Public\File\SomeScript.ps1 Arg1 %1 Arg2 %2 Arg3 %3 Arg4 %4""' -Verb RunAs}"

The Batch File echos the values I'm giving. But after that nothing happens. So I'm not sure if I'm passing the Arguments correctly.

Edit #1 - Solution

So this is the final Code, I tried it with 4 params.

PowerShell -NoProfile -ExecutionPolicy Bypass -Command "Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File \"C:\Public\File\SomeScript.ps1\" \"%1\" \"%2\" \"%3\" \"%4\"' -Verb RunAs"

Calling the Batch File Like :

.\batchfile.bat Arg1 Arg2 Arg3 Arg4

CodePudding user response:

  • The arguments must be outside the quoted script path, ""C:\Public\File\SomeScript.ps1""

  • To be safe, you should double-quote the arguments too.

  • Use \" to escape embedded double quotes when calling the CLI of Windows PowerShell (powershell.exe) as in your case), and "" for PowerShell (Core) (pwsh.exe).

    • Note: Depending on the specific values of the pass-through arguments, use of \" with Windows PowerShell can break, due to cmd.exe's limitations; the - ugly - workaround is to use "^"" (sic).

Therefore (limited to passing %1 for brevity):

PowerShell -NoProfile -ExecutionPolicy Bypass -Command "Start-Process PowerShell '-NoProfile -ExecutionPolicy Bypass -File \"C:\Public\File\SomeScript.ps1\" Arg1 \"%1\"' -Verb RunAs"

As an aside: There's no reason to use & { ... } in order to invoke code passed to PowerShell's CLI via the -Command (-c) parameter - just use ... directly, as shown above. Older versions of the CLI documentation erroneously suggested that & { ... } is required, but this has since been corrected.

  • Related