2

I just asked about a problem and the suggested code has some obscure points for me.

Specifically on this line of code

powershell.exe -c "Start-Process -Verb RunAs cmd /k, ('%~f0' -replace '[ &]', '^$0')"
  1. I would like to know what the comma after the cmd /k represents. What's this? How does it work? Is there a link to the documentation explaining this ?

  2. What's is the $0 in the last part. '^$0')"


Palle Due
  • 5,929
  • 4
  • 17
  • 32
Einstein1969
  • 317
  • 1
  • 13
  • 1
    I realize I forgot to answer your second question: `-replace '[ &]', '^$0'` is an application of the [`-replace` operator](https://stackoverflow.com/a/40683667/45375), and `$0` (`$&` would work too) is a placeholder for what the regex `[ &]` matches, i.e. either a space char. or `&` – mklement0 Oct 03 '21 at 22:49

1 Answers1

4

The Start-Process call embedded in your Windows PowerShell CLI (powershell.exe) call uses positional parameter binding, for brevity:

  • cmd, as the first positional argument, binds to the -FilePath parameter, i.e. the name or path of the executable to launch.

  • /k, (...), as the second positional argument, binds to the -ArgumentList parameter, which accepts an array of arguments to pass the target executable, whose elements are separated with ,

Start-Process then builds a command line behind the scenes, by joining the -FilePath argument and the -ArgumentList array elements with spaces, and launches it.

As an aside:

  • The way Start-Process builds the command line is actually broken, because no on-demand quoting and escaping is performed - see this answer for background information; in your specific case, however, the problem doesn't surface.

  • To work around the bug it is actually preferable in general to pass a single string to -ArgumentList that contains all arguments to pass; however, in this case that would have complicated quoting (you'd need an embedded "..." string or an explicit string-concatenation expression), so the simpler solution of enumerating the arguments with , was chosen.

  • See this answer for how to discover a given cmdlet's positional parameters; in short: invoke it with -? (Start-Process -?) and, in the relevant parameter set, look for the parameters whose names are enclosed in [...]; e.g.
    Start-Process [-FilePath] <System.String> [[-ArgumentList] <System.String[]>] ...

mklement0
  • 382,024
  • 64
  • 607
  • 775