powershell replace special characters

痴心易碎 提交于 2019-12-11 17:44:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!