2

I'm working on command which looks something like below -

$command="Path to Command / Bat file"  
$delim = [RegEx]::Escape("|")

(Get-ChildItem -Path .\ -Force).Name | % { &"$command"
".\$_" "$delim" "..\<SomePath>\$_.html"}

Issue am facing is with Passing the delim value which is Pipe in this case. Delim is the second argument to my command.

What's happening is the "..\\$_.html" is getting executed as an executable but it must be passed as third argument.

2 Answers2

1

Simply quote the | character to pass it to an external program. The quoting is needed to tell PowerShell that | is to be interpreted literally rather than as the pipeline operator.

PS> 'a|b' | & findstr /L '|'  # findstr.exe sees a literal | char.; & is optional here
a|b  # Literal '|' was found in input string 'a|b'

The only time additional work is needed is if the target program itself treats unquoted |[1] as having special meaning, notably when invoking cmd.exe or a batch file.

The most robust solution is to pass a whole command line as a single string to cmd.exe:

PS> cmd /c 'echo "|"'
"|"

(It is a quirk of cmd.exe's internal echo command that the double quotes are retained in this case.)

Even batch files can be called this way, which additionally also enables working around a problem with unreliably reported exit codes - see this answer.

cmd /c 'someFile.cmd "|" & exit'

[1] Even though '|' is quoted in the PowerShell command line above, behind the scenes PowerShell passes it unquoted, which it does whenever an argument has no embedded spaces.

mklement0
  • 382,024
  • 64
  • 607
  • 775
0

Got the answer to my problem. We need to use it in the following way instead regular expression. This is because the 'c' engine does not support regex separators.

$command="Path to Command / Bat file"  

(Get-ChildItem -Path .\ -Force).Name | % { &"$command"
".\$_" `"`|`" "..\<SomePath>\$_.html"}