DarkLite1 DarkLite1 - 3 months ago 38
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
$MyVariable
but needs to be addressed like
$MyVariable.User.Name
.

Anyhow, the code below demonstrates the problem.

HTML Input file

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


Code

$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
$ExecutionContext.InvokeCommand.ExpandString($Template)


Error

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


How is it possible to use the variable
$Object.User.GivenName
in the text file and have it populated with the proper value?

Answer

$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
$ExecutionContext.InvokeCommand.ExpandString($Template)

and use those in your template:

Dear $GivenName
Thank you for joining the program.
Comments