Home > front end >  In Powershell what the comma is for, how it works in this code example?
In Powershell what the comma is for, how it works in this code example?

Time:10-04

I just asked for a problem and the suggested code has some obscure points to 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')"


CodePudding user response:

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[]>] ...

  • Related