2

I am trying to write a Windows batch file which will replace occurrences of angled brackets (><) with a newline in between.

I am new to PowerShell, but in searching though possible solutions, I have found the following works from PowerShell:

(get-content input.txt) -replace "><", ">`n<"  | set-content output.txt

To use this within a windows batch, I need to wrap it inside

    powershell -command "arguments"

So the final command is something like:

powershell -command "(gc input.txt) -replace '><', '>`n<'  | sc output.txt"

However, this of course does not work because the single quotes around the replace text causes the grave quote escape character to be treated literally.

I have searched far and wide on the correct combination of escape characters to use to allow the PowerShell escape character to be recognised and have found a similar answer in here, but when I try this suggestion, I get a "< was unexpected at this time" error. I think what I need is more complicated because my search string also contains the angled brackets.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
JohnG
  • 31
  • 2

3 Answers3

1

Look at the powershell.exe command line options. You can use a script block:

powershell -command {(gc input.txt) -replace "><", ">`n<"  | sc output.txt}
Shawn Esterman
  • 2,292
  • 1
  • 10
  • 15
  • You can only use a scriptblock argument if you are already in PowerShell; the command prompt interpreter doesn't know what a PowerShell scriptblock is, and this doesn't work in a batch file, and tries to run `sc.exe` for managing services. – TessellatingHeckler Nov 09 '17 at 04:50
1

Avoid using the escape character and double quotes?

powershell -command "(gc d:\t\input.txt) -replace '><', ('>'+[char]10+'<')  | sc d:\t\output.txt"
TessellatingHeckler
  • 27,511
  • 4
  • 48
  • 87
1

I have solved the problem. I also used delayed expansion, so the final command is:

powershell -Command "(gc !inputfile!) -replace (\"^>^<\", \"^>`n^<\")  | sc !outputfile!"

So it actually uses three different types of escape characters! Combination of \ and ^ and `.

I wish I could say I worked it out logically, but in the end it was just a random attempt using different escapes on the ><.

But this is now a good reference on how to use PowerShell inside Windows batch without using single quotes which turn escape characters into literals.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
JohnG
  • 31
  • 2