我们正在尝试为我们的脚本创建输入文件,而不是使用此处的字符串(@"E-mail text"@
)对代码中的电子邮件文本进行硬编码。但是,填充一个不像$MyVariable
那样简单明了的变量似乎很难,但需要像$MyVariable.User.Name
那样解决。
无论如何,下面的代码演示了这个问题。
HTML输入文件
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
$ExecutionContext.InvokeCommand.ExpandString($Template)
错误
Exception calling "ExpandString" with "1" argument(s): "Object reference not set to an instance of an obj
ect."
如何在文本文件中使用变量$Object.User.GivenName
并使用适当的值填充它?
答案 0 :(得分:0)
$ExecutionContext.InvokeCommand.ExpandString()
扩展字符串中的变量。它不评估复杂的表达式。基本上,为了让事情按照你想要的方式工作,你需要创建单独的变量
$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)
并使用模板中的内容:
Dear $GivenName Thank you for joining the program.