Search code examples
powershellbatch-filesyntaxquoting

How I do invoke a PowerShell Start-Process command with arguments that require quoting from a Command Prompt / batch file?


I am getting this error when trying exec one command in PowerShell:

I am trying to exec this command:

powershell.exe Start-Process -FilePath "C:\Windows\System32\attrib +h +s "%CD%"" -Verb runAs

Can someone please help me figuring out why this is happening and how to solve it?


Solution

  • Can someone please help me figure out why this is happening?

    The -FilePath parameter of the Start-Process cmdlet expects the name or path of an executable file by itself, not an entire command line.

    The arguments to pass to the executable specified via -FilePath must be passed separately, as an array, via the -ArgumentList (-Args) parameter.

    When calling from cmd.exe (a batch file), it's conceptually cleaner to pass the entire command line to be evaluated by PowerShell in a single, "-enclosed argument:

    powershell.exe -Command "Start-Process -Verb RunAs -FilePath attrib.exe -Args +h, +s, '\"%CD%\"'"
    

    Note the need to escape the %CD% value doubly, by enclosing it in ' for the sake of PowerShell first, then in \" inside that: The outer ' ensures that PowerShell itself recognizes the value as a single argument, and the embedded \" quoting ensures that the ultimate target program, attrib.exe, sees the value as a single argument too.

    This need for double escaping is unfortunate and shouldn't be necessary - it is discussed in this GitHub issue.