Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 850
Tobi123 Avatar asked Jul 10 '15 08:07

Tobi123


3 Answers

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
like image 153
Vesper Avatar answered Nov 10 '22 06:11

Vesper


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.

like image 42
Enrico Campidoglio Avatar answered Nov 10 '22 07:11

Enrico Campidoglio


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
like image 1
Dave Sexton Avatar answered Nov 10 '22 06:11

Dave Sexton