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 :)

Lauren Yim
  • 12,700
  • 2
  • 32
  • 59
Subscaper
  • 232
  • 5
  • 15

1 Answers1

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.

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • 2
    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 Sep 22 '21 at 14:57
  • 3
    @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. – mklement0 Sep 22 '21 at 15:15