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?
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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With