0

I have a pipe line already constructed and retrieving my expected results. I want to now replace a whole line if a certain match is found then export the whole lot to a text file, with changes if it were required, or without changes if wasn't required. I need help constructing the right forloop to search for the text on each line, and replace that line if needed.

In the example code below. I want it to go through my file whitch is loaded into $items variable, find any line that starts with ID_ and replace that line with whatever string I put in

foreach ($item in $items) {
if ($item -like "ID_*") {
# Item match, replacing text.
$item -replace $item,"<ReplacedText>"
Out-File New.txt

} else {
# No matches found, continue exporting
Out-File New.txt
}
}

Please and thank you!

  • You can replace all of that with something like this `$items -replace '^ID_.*', 'Replacement String' -join "\`n" | Set-Content new.txt -NoNewline` – Daniel Aug 13 '22 at 05:13
  • Hey mate!, thank you very much, that's exactly what I'm after... cheers!! – UniqueTurbo Aug 13 '22 at 06:11
  • If you really have a correctly setup [PowerShell pipeline](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_pipelines) you better don''t choke it with a [`foreach` statement](https://stackoverflow.com/q/29148462/1701026) but simply do this: `... -replace '^ID_.*',$ReplacedText |Out-File New.txt` – iRon Aug 13 '22 at 06:21

0 Answers0