问题
I am farely new to powershell but I am trying to replace certain characters within .xml files. Looks like I stumble with the first steps already.
e.g. I'll try to replace:
<?xml version="1.0"?>
with
<?xml version="2.0"?>
Below you'll find the code I wrote so far:
Get-Childitem "C:\Users\jp\Desktop\Test" | ForEach-Object {
$Content = Get-Content $_.fullname
$Content = ForEach-Object { $Content -replace "(<?xml version=`"1.0`"?>)","(<?xml version=`"2.0`"?>)" }
Set-Content $_.fullname $Content -Force
}
The problem is that this is just the start of the strings I have to replace. Is there a way to replace any text within a certain range independent from the characters inside?
I wonder how to replace a complete string no matter what special characters I have inside. Thanks in advance.
回答1:
Use the Escape method to escape special characters at run time. You don't need to escape the replace pattern:
(Get-Content c:\dump\xml) |
ForEach-Object {$_ -replace [regex]::Escape('<?xml version="1.0"?>'),'<?xml version="2.0"?>'} |
Set-Content c:\dump\xml
回答2:
Hi there are lots of ways to do regex matches you could simply change your code to the one below.
The \ just escapes the special regex charters so that the match part works.
Get-Childitem "c:\dump\xml" | ForEach-Object {
$Content = Get-Content $_.fullname
$Content = ForEach-Object { $Content -replace '(<\?xml version="1\.0"\?>)','<?xml version="2.0"?>' }
Set-Content $_.fullname $Content -Force
}
来源:https://stackoverflow.com/questions/11899310/powershell-replace-special-characters