1

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.

Any help appreciated :)

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Hi mklement0, I am not that big of a Powershell user but I do read the ones that are tagged with batch-file. From time to time I see this double usage of executing Powershell. What is the purpose of that?
@Squashman, it is necessary in order to create an elevated process, which cannot be done directly: the first powershell call invokes Start-Process -Verb RunAs, which creates an elevated (run as admin) process. In this case, it is another PowerShell process, but you can use the technique to launch any program with elevation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.