0

I am finding/replacing words in Powershell. I am curious about the order of replacement.

Want to have it Sequentially replace Test1 with Test2, and Then replace certain string combination of Test2 with Test3 (see below).

1) Just curious if its safe writing code below? Or Does Powershell run things simultaneously, thus breaking my Required Sequence replacement pattern?

It seems to be work, just want to be 100% sure. Otherwise, I can write another foreach loop, after the first replacement is complete.

2) Also, do I need the pipe delimiters below? Not sure what they do, inheriting this script from previous programmer, attempting to google and research powershell.

#Replace words in file
$TestFiles = Get-ChildItem $DBContextDestination   *.cs -rec
foreach ($file in $TestFiles )
{
    (Get-Content $file.PSPath) |
    Foreach-Object { $_ -replace "abcd", "1234" } |
    Foreach-Object { $_ -replace "Test1;", "Test2" } |
    Foreach-Object { $_ -replace "Class Test2 Object", "Class Test3 Object" } |
    Set-Content -Encoding UTF8  $file.PSPath
}
  • 1
    For each individual input item, the commands in a pipeline will execute in order, ie. no input string will ever reach the 3rd `ForEach-Object` block before having passed through the 2nd and so on – Mathias R. Jessen Jun 16 '20 at 17:09
  • hi @MathiasR.Jessen thanks, feel free to write in answer, and I can send points, do I also need the | pipe delimiters at the end? Does that ensure the sequence? –  Jun 16 '20 at 17:10
  • 1
    Their not really "delimiters", but yes, you do need `|` in order to "bind" them together. The answer to the duplicate I've closed it against explains how the pipeline works – Mathias R. Jessen Jun 16 '20 at 17:13

1 Answers1

1

Yes, unlike pipes in unix nothing runs in the background. If one object is sent, it goes sequentially left to right through the pipeline. You can also chain the replaces. Is there supposed to be a semicolon after Test1?

(Get-Content $file.PSPath) -replace "abcd", "1234" -replace "Test1;", 
  "Test2" -replace "Class Test2 Object", "Class Test3 Object"
js2010
  • 23,033
  • 6
  • 64
  • 66