I have a problem with the variable. I want to put it in the content of the email, unfortunately all attempts end in failure. In Powershell this is my first script, I have experience in programming. I want to add $PasswordTillExpired variable in the content of the email:
$emailBody = @"
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
</head>
<body>
<b><p>Your password will expire soon! $PasswordTillExpired</p></b>
<p>Please change password at xxx password reset'</a> or contact Helpdesk.</p>
<p><br>More information about changing your password and instructions can be found</p></b>
<p>Greetings,</p>
<p>Helpdesk IT</p>
</body>
</html>
"@
Yes, only this variable is defined later in the loop, so you don't 'update' the email content. – markiewicz36 5 mins ago
Variable Expansion in PowerShell works differently. In order to expand a variable inside a string, the Variable must be defined before you assign the string.
To illustrate, this will not work.
$Body = " Hello, $user !"
$user = "FoxDeploy"
Write-Host $Body
" Hello, !"
While this will:
$user = "FoxDeploy"
$Body = " Hello, $user !"
Write-Host $Body
" Hello, FoxDeploy!"
You simply need to move your variable assignment down into an area in your script where $PasswordTillExpired
has a meaningful value.
To Preserve your Present Approach
If you really want to use the approach you have today, of assigning the e-mail body at the top of the script, you could use -Replace
to swap a token out.
So, you'd change $PasswordTillExpired
to something like %PasswordTillExpiredToken
, then make a new instance of the e-mail body when you need it, like this:
$thisEmailBody = $emailBody -replace "%PasswordTillExpiredToken", $PasswordTillExpired
That will give you a new $thisEmailBody
customized for that user.