Why does a trailing backslash break Powershell parameter parsing?

Viewed 864

I've been pulling my hair out trying to figure out why Powershell was ignoring a command line parameter and I think I finally found that somehow a trailing backslash on a string parameter confuses parameter parsing.

I have

param (
    [Parameter(Mandatory=$true)][String]$p1,
    [Parameter(Mandatory=$true)][String]$p2
)

Write-Output "p1:$p1, p2:$p2"

Ultimately, I need to invoke something like this from the Windows task scheduler which means using powershell.exe as the program and adding this script and arguments as args.

In production, p1 is a file path. So I try:

PS C:\source> C:\Windows\System32\windowspowershell\v1.0\powershell.exe -ExecutionPolicy Bypass -File  .\myScript.ps1 -p1 'C:\Program Files\' -p2 asdf

cmdlet myScript.ps1 at command pipeline position 1
Supply values for the following parameters:
p2:

Why the prompt? The parameter is right there. I eventually stumbled on removing the trailing backslash for p1:

PS C:\source> C:\Windows\System32\windowspowershell\v1.0\powershell.exe -ExecutionPolicy Bypass -File  .\myScript.ps1 -p1 'C:\Program Files' -p2 asdf
p1:C:\Program Files, p2:asdf

Is this a bug?

1 Answers

This works for me in cmd (double backslash and double quotes). I guess the backslash is an escape character for the powershell command line options.

C:\Windows\System32\windowspowershell\v1.0\powershell.exe -ExecutionPolicy Bypass -file .\myScript.ps1 -p1 "C:\Program Files\\" -p2 asdf

p1:C:\Program Files\, p2:asdf
Related