I'm struggling with a seemingly simple task in PowerShell. I've got a file named file.txt that contains a string with a variable: "Hello, today is $(get-date)!". When I use `get-content file.txt`, it retrieves this as a plain string rather than evaluating the variable. I need a way to get the output as something like "Hello, today is Tuesday 30 September 2025". This is important as I want to avoid manually building HTML around multiple variables for an email I'm preparing.
3 Answers
Another approach is to utilize templates for replacement. By doing something like:
```powershell
$replaceValues = @{
Name = $name
Email = $email
Date = Get-Date
}
$template = get-Content -raw template.html
foreach ($replaceItem in $replaceValues.GetEnumerator()) {
$searchString = "%%$($replaceItem.Key)%%"
$template = $template -replace $searchString,$replaceItem.Value
}
Write-Output $template
```
This way, you can control what gets executed and it limits security risks. You can have your template text look like this: "Hello, today is %%date%%!".
If you're open to alternatives, you could consider using replacement strings instead. For instance, change your content to use something like this:
```powershell
$x = get-content file.txt
$x.replace("{{GETDATE}}",(Get-Date))
```
Make sure the replacement strings are unique enough to avoid conflicts.
If you want to treat your string as a PowerShell script, save it as file.ps1 and just run:
```powershell
$x = .file.ps1
```
It evaluates the contained expressions directly!
That works too, but it's a bit more complicated. Just looking for ways to avoid extra steps!

That's a neat idea, but it does seem slightly tedious compared to the first method. Still, I see its appeal for safety.