$xmlFilePath = 'Desktop\original.xml'
$xmlfile = get-content $xmlFilePath
$xmlfile -Replace 'box','boxes'
the original.xml contain some data and i want to replace "boxes" value in xml file with 'box'. power shell gives output as expected but doesn't change the actual file original.xml. I get the changed output in power shell but when i view the file the desktop the file doesn't have the changes.
You can use Get-Content to read a file's contents into memory, apply the string replacements, and then pass the contents through the pipeline to Set-Content.
$xmlFilePath = 'Desktop\original.xml'
(Get-Content $xmlFilePath) -replace 'box','boxes' | Set-Content $xmlFilePath
The use of ()
around the Get-Content
command is necessary to prevent the parser from interpreting -replace
as a parameter.
Note that if you want to read in a file's contents as a single string, you can use the -Raw
switch on Get-Content
. Not using -Raw
could add extra new line characters.