2

I need a PowerShell script that search in XML files for <?xml version="1.0" encoding="UTF-8"?> and remove it. I tried:

(Get-Content $file) | 
    Foreach { $_ -Replace  '<?xml version="1.0" encoding="UTF-8"?>', "" } | 
    Set-Content $file;

but it doesn't work.

3 Answers 3

2

This doesn't work because -replace is using regex (you would have to escape your string in order to get it work). However, you can also use the .Replace static method for strings which doesn't use regex:

(Get-Content $file -raw).Replace('<?xml version="1.0" encoding="UTF-8"?>', '') | 
    Set-Content $file;

Note that I am using the -raw switch of the Get-Content cmdlet to load the file as a single string (instead of a string array) - so you don't need to iterate over the lines but can replace everything at once.

Sign up to request clarification or add additional context in comments.

5 Comments

and for exemple to remove (Get-Content $output -raw).Replace('</Export>', '') | Set-Content $output; (Get-Content $output -raw).Replace('<Export/>', '') | Set-Content $output; (Get-Content $output -raw).Replace('<?xml version="1.0" encoding="UTF-8"?>', '') | Set-Content $output; is there a way to do it simpler?
@MartinhoVasconcelos You are changing your requirements in the comments. Please stick to your first issue as the accepted answer doesn't match your question the way this one does. If that was important you should have edited that into the question in the first place.
You can concat multiple replace together like: (Get-Content $output -raw).Replace('</Export>', '').Replace('<Export/>', '').Replace(....) | Set-Content $output. But since you are editing XML, it may be better to do this with XML methods (depends on your requirement).
-raw is not util here because you use ()
@Esperento57 True, its not necessary
1

Building on @MartinBrandl's answer, if you need to remove multiple parts, you could do this:

$toRemove = '</Export>', '<Export/>', '<?xml version="1.0" encoding="UTF-8"?>'

$content = Get-Content $file -Raw

foreach($part in $toRemove) {
    $content = $content.Replace($part, '')
}

$content | Set-Content $file

Comments

1

you can escape your string too like this

(Get-Content $file) | 
    Foreach { $_ -Replace  [Regex]::Escape('<?xml version="1.0" encoding="UTF-8"?>'), '' } | 
        Set-Content $file;

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.