Search code examples
powershellselectlinecpu-word

select lines begin with and finish with


I have a Powershell script with XAML code (for display some windows and buttons) I try to replace a value of all lines begin with $computer.selectedvalue and finnish by ",1" in a text file.

My text file content :

COMPUTER01,SITE01,PRINTER01,1
COMPUTER05,SITE02,PRINTER01,0
COMPUTER01,SITE03,PRINTER08,1

end with ,1 is the printer by default and ,0 is the secondary printer

Powershell code :

$PLPrinterArray = Get-Printer  -ComputerName srvprint | select name
foreach ($PLPrinterArray in $PLPrinterArray) { 
  [void]$WPFCboPL.items.add(",PL,$($PLPrinterArray.Name)")
} 

$LDAPComputerArray = Get-ADComputer -filter * -SearchBase"OU=Ordinateurs,DC=MyDC,DC=Mydomain,DC=org" -Properties name
foreach ($LDAPComputerArray in $LDAPComputerArray) { 
  [void]$WPFCboComputer.items.add($($LDAPComputerArray.Name))
}

$WPFBoutonDefaut.Add_Click({
  #If (Get-Content C:\Users\User\desktop\test.txt
  $($WPFCboComputer.selectedvalue)^ ",1$") {
  #-replace ",1",",0"}
  Add-Content -path "C:\Users\User\Desktop\test.txt"
  -value"`n$($WPFCboComputer.selectedvalue)$($WPFCboPL.SelectedValue)$($WPFCboLN.SelectedValue),1"
})

Is it possible to do this and especially in a Button.Add.Click?

Thanks in advance ;-)


Solution

  • I suggest using a switch statement with the -Regex and -File options:

    $WPFBoutonDefaut.Add_Click({
    
      $file = 'C:\Users\User\desktop\test.txt'
    
      # Process the input file line by line with regex matching,
      # and collect the potentially modified lines in an array.
      [array] $modifiedlines = 
        switch -Regex -File $file {
          "^($($WPFCboComputer.SelectedValue),.+,)1$" { $Matches[1] + '0' }
          default { $_ } # pass through
        }
    
      # Save the modified lines plus the new line back to the file.
      # Note: Use -Encoding as needed.
      Set-Content $file -Value (
        $modifiedLines + "$($WPFCboComputer.SelectedValue)$($WPFCboPL.SelectedValue)$($WPFCboLN.SelectedValue),1"
      )
    
    })