Change content in HTML File

Hi

I have some html files in a directory so i want to find some content in every file and replace it following requirement should be accomplished

1.If you found the “class=name” css parameter replacement should not be happen (ignore it)

style="class=name;font-size:10pt;font-family:"Arial","sans-serif";color:#000; font-weight:bold; ">

2.if you found “font-weight:bold” i had to replace it with font-weight:normal
3.Output new file

following is the script i tried

Foreach-Object {
$original_file = Get-ChildItem ‘D:\Documents\Signature\Test\Support*.html’ -Recurse
$end = $original_file.GetValue(0).ToString()
$destination_file = $end

$FileContent=Get-Content $original_file

if($FileContent -icontains 'class=name'){
    $FileContent -replace 'font-weight:bold', 'font-weight:bold'
}elseif($FileContent -icontains 'font-weight:bold'){
    $FileContent -replace 'font-weight:bold', 'font-weight:normal' 
}`

} | Set-Content $destination_file

Thanks

$FileContent isn’t a string - it’s a collection of strings, with one object for each line in the file. You can’t readily execute comparison operators against a collection. It’s like taking a bunch of cars and asking, “is this red?” What you’ll probably need to do is use a ForEach loop to enumerate each line in the file:

ForEach ($line in $FileContent) {

}

Further, the -contains operator isn’t a string comparison operator. I suspect you’re looking for -ilike instead. Read about_comparison_operators in PowerShell (it’s a help file).

Additionally, Set-Content isn’t necessarily the right command for outputting. It’s intended to set the entire content of the file, and you’re going to end up giving it one line at a time. Look into Out-File and the -Append parameter, instead, so you can output one line at a time.

Hi Kasun,

Additionally you are running Get-ChildItem -recurse within the foreach block which will give you a collection of FileInfo objects. Then you pass it to get-content which ultimately creates an amalgamation of all the files rather than individual files.

Try running get-childitem outside of the foreach and using a nested foreach to cycle through each line as Don suggested.

# Add filters to Get-ChildItem as necessary
Get-ChildItem -Recurse | ForEach-Object {
     $FileContent = Get-Content....
     
     ForEach ($line in $FileContent) {
          ...
     }
}

Hi Guys

Thanks for your valuable comment i ll look in to this

Thanks

Although I don’t think it a good option because it will remove any good formatting if the code is well structured. You could type cast your content as a string and do a complete replace or use -join to make it a single string. I agree with Don and Chris however that looping through the content would be best.

$FileContent=Get-Content $original_file
$StringFileContent = [string]$FileContent

or

$FileContent=Get-Content $original_file
$StringFileContent = $FileContent -join ""