Home > Enterprise >  Powershell making the change I want but it deletes everything else in the .pgm file
Powershell making the change I want but it deletes everything else in the .pgm file

Time:02-26

I am trying to modify a .pgm file sample data below.

<?xml version="1.0" ?>
<Document>
<Attachments>
<File Name="H:\PT000224.pdf"/>

Above I need to change the H: in the file name above to an L: and have it loop through multiple documents and make the same change. I have started with this.

Get-ChildItem "C:\Users\test\Desktop\Change PGM" | ForEach-Object {
$content = Get-Content $_.FullName
$content = ForEach-Object { $content -like "*H:*" -replace "H:","Z:"}
Set-Content $_.FullName $content -Force
}

It goes through everything and changes the value that I want but deletes everything else in the.pgm file.

CodePudding user response:

Remove the -like operation - if the input string doesn't contain H:, -replace will simply return the string as-is, so there's no need to "pre-filter" the data:

PS ~> @('H:', 'I:') -replace 'H:','Z:'
Z:
I:

So you can simplify your code as follows:

Get-ChildItem "C:\Users\test\Desktop\Change PGM" | ForEach-Object {
  # read file contents
  $content = Get-Content $_.FullName
  # replace and write back to disk
  $content -replace "H:","Z:" |Set-Content $_.FullName -Force
}
  • Related