Powershell Error: Method invocation…doesn't contain a method named 'replace'

▼魔方 西西 提交于 2020-01-13 10:27:05

问题


I want to search and replace a string in an xml file using PowerShell. I tried this:

(gc d:\test.xml).replace('1234','xxxx')|sc d:\test.xml

This works fine for my test.xml file. The content of my test.xml file is:

uehjduehduhfeuf xxxxxxxx hallo "1234"

But that file is only for testing. I want to edit a server.xml form my tomcat server in this way and if I'm using exactly the same command mentioned obove I get this error message:

Method invocation failed because [System.Object[]] doesn't contain a method named 'replace'.

Does anybody know what's the problem?


回答1:


You can also use [System.IO.File]::ReadAllText($filename) to get a single string out of a file, with all newlines and other symbols.

[System.IO.File]::ReadAllText("d:\test.xml").replace('1234','xxxx')|sc d:\test.xml



回答2:


When you store the output of the Get-Content cmdlet in a variable, the data is stored as an array of type Object (i.e. Object[]) with one element for each line in the source file. Here's from the documentation:

When Get-Content reads a text file and stashes the contents in a variable, the data is stored as an array, with each line in the file (determined by the presence of a carriage return-linefeed character) representing a single item in the array.

When you put parenthesis around an expression, PowerShell creates a temporary variable, which in the case of Get-Content ends up being of type Object[].

In order to replace text from the source file, you need to iterate through the array and manipulate each line separately:

gc d:\test.xml | foreach { $_ -replace "1234", "xxxx" } | sc d:\test.xml

Or you can invoke the .NET BCL directly, as @Vesper pointed out.




回答3:


Get-Content will give you an array of strings try using the raw switch like so:

(gc d:\test.xml -raw).replace('1234','xxxx')|sc d:\test.xml



回答4:


Thank you for the explanation @Enrico Campidoglio!

In addition to your answer, some characters (such as PIPE in my case) will need to be escaped:

(gc d:\test.xml -raw).replace('\|',',')|sc d:\test.xml

I would have added this as a comment but I can't yet...



来源:https://stackoverflow.com/questions/31335614/powershell-error-method-invocation-doesnt-contain-a-method-named-replace

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