Home > Net >  Powershell - replace variable with it's content in HTML file
Powershell - replace variable with it's content in HTML file

Time:11-19

I have HTML file:

1.html

!DOCTYPE html>
<html>
    <head>
        <title>Password Reminder</title>
    </head>
    <body>
    
        <p>
        Dear user, your password expires in: <strong>$($days)</strong> days.
        </p>
    </body>
   </html>

I created function which reads file content and replace $days variable with actual variable value.

function ReadTemplate($days) {
    $template_content = Get-Content "C:\PasswordReminder\1.html" -Encoding UTF8 -Raw
    #$template_content = [IO.File]::ReadAllText($template)
    $template_content = $template_content -replace "{}",$days
    return $template_content
}

But when calling it

$content = ReadTemplate -days 2

Instead of Dear user, your password expires in: 2 days.

I'm getting

Dear user, your password expires in: $($days) days.

Instead of $($days) specified {0} but nothing

CodePudding user response:

Try $template_content = $template_content.replace('$($days)',$days)

CodePudding user response:

You can use Escape method:

$template_content -replace ([regex]::Escape('$($days)')), $days

CodePudding user response:

As $($days) is in fact a valid PowerShell variable syntax, you probably just want to substitute it:

$Days = 17
$ExecutionContext.InvokeCommand.ExpandString($template_content)
  • Related