Calling PowerShell.exe -Command ScriptName and Parameters with Commas

Bit of an obscure one this, but I hit it recently and wasted some time on it so I thought it might be useful for someone, somewhere, someday.

If you need to call a PowerShell script via a command line style prompt (maybe in a scheduled task or an external system like vCenter Orchestrator) there are a number of different options.

I was troubleshooting a problem where an existing system was failing with a command along the lines of this:


C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -Command C:\\Scripts\\TestComma.ps1 -input1 'banana,pear'

and would fail with the following error:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe : C:\scripts\TestComma.ps1 : Cannot process argument transformation on parameter At line:1 char:1 + C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Command C:\scripts\Te … + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (C:\scripts\Test…n on parameter :String) [], RemoteException + FullyQualifiedErrorId : NativeCommandError

‘Input1’. Cannot convert value to type System.String. At line:1 char:34 + C:\scripts\TestComma.ps1 -input1 banana,pear + ~~~~~~~~~~~ + CategoryInfo : InvalidData: (:) [TestComma.ps1], ParameterBindi ngArgumentTransformationException + FullyQualifiedErrorId : ParameterArgumentTransformationError,TestComma.p s1

So it looked like it was having an issue with the string being supplied as the parameter ‘banana,pear’ even though there is normally no issue with this being a string. I eventually tracked it down to being a problem with the comma - with no comma there is no issue.

Note: This is only an issue when being called by powershell.exe. When used in a standard PowerShell console or script there is no issue with this text being a string:


('banana,pear').GetType()

There are a number of ways round this:

1) Run it from cmd.exe

Sacrilege I know, but the system I was working with effectively was calling it from cmd.exe which subsequently didn’t experience the issue.

 

2) Escape the comma

Escape the comma character like so


C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -Command C:\\scripts\\TestComma.ps1 -input1 'banana\`,pear'

3) Use the File parameter instead

The better solution in my opinion is to use the File parameter. I typically use this anyway rather than the Command parameter. It was introduced in PowerShell v2 and has been my preferred way of doing this kind of thing since then.


C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -File C:\\scripts\\TestComma.ps1 -input1 'banana,pear'