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.

1

3 Answers 3

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}
Sign up to request clarification or add additional context in comments.

1 Comment

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.
1

Avoid using the escape character and double quotes?

powershell -command "(gc d:\t\input.txt) -replace '><', ('>'+[char]10+'<')  | sc d:\t\output.txt"

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.