DarkLite1 DarkLite1 - 1 year ago 100
PowerShell Question

Expand variable in file

We're trying to create input files for a script of ours instead of hard coding the text of an e-mail within the code with here strings (

@"E-mail text"@
). However, it seems really difficult to populate a variable that is not plain and simple like
but needs to be addressed like

Anyhow, the code below demonstrates the problem.

HTML Input file

Dear $($Object.User.GivenName)
Thank you for joining the program.


$SamAccountNameManager = 'Mike'
$SamAccountNameUser = 'Bob'
$File = 'C:\Test.html'

$Object = [PSCustomObject]@{
User = Get-ADUser $SamAccountNameUser -Properties GivenName
Manager = Get-ADUser $SamAccountNameManager -Properties GivenName

$Template = Get-Content $File


Exception calling "ExpandString" with "1" argument(s): "Object reference not set to an instance of an obj

How is it possible to use the variable
in the text file and have it populated with the proper value?

Answer Source

$ExecutionContext.InvokeCommand.ExpandString() expands variables in a string. It does not evaluate complex expressions. Basically, to make things work the way you want you need to create individual variables

$GivenName = Get-ADUser $SamAccountNameUser -Properties GivenName |
             Select-Object -Expand GivenName
$Manager   = Get-ADUser $SamAccountNameManager -Properties GivenName |
             Select-Object -Expand GivenName

$Template = Get-Content $File | Out-String

and use those in your template:

Dear $GivenName
Thank you for joining the program.