0

I read a xml file and want to replace three strings.

My Code:

foreach ($file in Get-ChildItem $files){
 (Get-Content $file) | Foreach-Object {
  $_ -replace 'TABLE_NAME="\$ZoneProdukt\$', ('TABLE_NAME="' + $ZONPRODLANG)`
    -replace 'OPTION="Copy" ', '' `
    -replace ('<JOB ','<JOB TIMETO="TEST" ') | ? {$_ -notlike "*TIMETO=`""}
 } |  Set-Content ($destination_folder + $file.name)
}

the last replace provides only the half of the result I expect.

If there are lines containing "JOB" and "TIMETO" they will not be displayed (because of Where-Object)

How to keep lines if the mentioned "TIMETO"-Attribute already exists?

examples:

source line in file (without "TIMETO"):

<JOB JOBISN="30" USER="testuser">

correct replace:

<JOB TIMETO="TEST" JOB JOBISN="30" USER="testuser">

....

....

source line in file (with "TIMETO"):

<JOB JOBISN="30" USER="testuser" TIMETO="0400">

replace -> this line will not be displayed !!

..

thanks in advance! br danijel

1 Answers1

1

You could use an if-statement in your ForEach-Object:

foreach ($file in Get-ChildItem $files){
 (Get-Content $file) | Foreach-Object {
    if($_ -like "*TIMETO=`""){
      $_ -replace 'TABLE_NAME="\$ZoneProdukt\$', ('TABLE_NAME="' + $ZONPRODLANG)`
        -replace 'OPTION="Copy" ', '' `
    }else{
      $_ -replace 'TABLE_NAME="\$ZoneProdukt\$', ('TABLE_NAME="' + $ZONPRODLANG)`
        -replace 'OPTION="Copy" ', '' `
        -replace ('<JOB ','<JOB TIMETO="TEST" ')
    }
 } |  Set-Content ($destination_folder + $file.name)
}

Manipulating xml using regex is generally bad practice. You should use Get-Content and cast as [xml], which will allow you to manipulate the object. Check out this this MSDN demo.

G42
  • 9,791
  • 2
  • 19
  • 34
  • the problem of that solution is that the other replaces(e.g. table_name and option) must be done regardless of whether "timeto" is matched in line. – Danijel de Vasco Mar 15 '18 at 14:58
  • @DanijeldeVasco Quick and dirty solution in edit. Seriously though, consider the object approach. – G42 Mar 15 '18 at 15:19