2

I have the following script which I try to run on various html files

$files = $args[0];
$string1 = $args[1];
$string2 = $args[2];
Write-Host "Replace $string1 with $string2 in $files";
gci -r -include "$files" | 
 foreach-object { $a = $_.fullname; ( get-content $a ) | 
    foreach-object { 
            $_ -replace "%string1" , "$string2" | 
            set-content $a
    }
}

in an attempt to edit this line found in all the files.

<tr><td><a href="sampleTest.html">TestCase</a></td></tr>

I call the script from powershell like this (it's called replace.ps1)

./replace *.html sampleTest myNewTest

but instead of changing sampleTest.html to myNewTest.html it deletes everything in the doc except for the last line, leaving all of the files like so:

/html

in fact, no matter what arguments I pass in this seems to happen. Can anyone explain this/help me understand why it's happening?

1 Answer 1

3

Your loop structure is to blame here. You need to have the Set-Content located outside the loop. Your code is overwriting the file at every pass.

....
 foreach-object { $a = $_.fullname; ( get-content $a ) | 
    foreach-object { 
            $_ -replace "$string1" , "$string2" |         
    } | set-content $a
}

It also might have been a typo but you had "%string1" before which, while syntactically correct, what not what you intended.

Could also have used Add-Content but that would mean you have to erase the file first. set-content $a used at the end of the pipe is more intuitive.


Your example is not one that uses regex. You could have used $_.replace($string1,$string2) with the same results.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.