How to escape all quotes in $* to pass it to PowerShell from CMD

224 Views Asked by At

I experience some problem with executing PowerShell command from CMD.

I have a function MyFunction in PowerShell which takes two parameters: Id and Text. Example:

MyFunction 12345 "Name = Karl"

I need to call this function from CMD:

powershell -Command . { MyFunction $* }

where $*: 12345 "Name = Karl"

But I get error:

A positional parameter cannot be found that accepts argument 'Karl'

The cause of it is quotes are being removed from passing parameters

enter image description here

I figured out I need to escape all quotes in passing parameters but I really don't know how to do it within $*. I'm not expert in CMD, could you please help me to solve the issue?

Update (12/25/2019)

I forgot to mention I'm creating an alias via doskey and I don't know how to escaping quotes within $*

MyFunction=powershell -Command . { MyFunction $* }
1

There are 1 best solutions below

1
On BEST ANSWER

doskey macros do not support pre-processing of arguments passed ($*), which is what is required in your case.

Preprocessing of the arguments is required, because you're using the PowerShell CLI's -Command parameter - of necessity, since you're calling a function - where the arguments undergo an additional round of parsing after PowerShell strips them of enclosing "...": the resulting values are concatenated and then interpreted as a piece of PowerShell code - and by that time what was originally "Name = Karl" is seen as 3 individual arguments, Name, =, and Karl. To solve that problem, you'd have to use embedded quoting, by passing "Name=Karl" as "\"Name = Karl\"" (sic) instead.

However, you wouldn't have that problem if you used -File instead of -Command, but that only works when you call a script file (*.ps1).

Here's a workaround:

  • Create an auxiliary *.ps1 file named, say, MyFunction.ps1, with the following content:
MyFunction $args

Be sure that function MyFunction is actually defined in your PowerShell sessions. By virtue of being a function, it takes precedence over a script with the same base name.

  • Then redefine your doskey macro as follows (adjust the path as needed; if you placed MyFunction.ps1 in a directory listed in $env:PATH, you don't need to specify a path):
doskey MyFunction=powershell -File C:\path\to\MyFunction.ps1 $*