0

I have a PowerShell file e.g. C:\MyPowerShell.ps1 and I would like to have the following line there:

$myNewVariable = "Lukas"

Where string Lukas will be taken from variable $name. The variable $name will be declared before I run a command to do this action. I would like to use another PowerShell command to do that.

$name = "Lukas" <br>
Add-Content C:\MyPowerShell.txt ???

Please help me ;-)

pmadhu
  • 3,373
  • 2
  • 11
  • 23
  • Where is "there"? On the first line of the file? Last line? In the middle somewhere? What's already in the file? – Mathias R. Jessen Aug 20 '21 at 12:23
  • ``'$myNewVariable = "Lukas"'` | Add-Content -Path 'C:\MyPowerShell.ps1'``. If you enclose the string in single quotes, PowerShell won't expand the variables inside, so the string is taken literally – Theo Aug 20 '21 at 12:23
  • @MathiasR.Jessen There means only this single line. – Lukáš Glod Aug 20 '21 at 12:44
  • @Theo But Lukas should be taken from another variable e.g. $name = "Lukas" and used in the command – Lukáš Glod Aug 20 '21 at 12:49
  • You would like to add the value of $name to the file C:\MyPowerShell.txt? If so, just pipe it... $name | Out-File c:\MyPowerShell.txt -Append – Dennis Aug 23 '21 at 19:53

2 Answers2

0

Use an expandable (interpolating) string ("...") in which you individually `-escape $ characters in tokens you do not want to be expanded as variable references / subexpressions; similarly, escape embedded " characters as `" ("" would work too):

$name = 'Lucas'
Add-Content C:\MyPowerShell.txt -Value "`$myNewVariable = `"$name`""

Alternatively, use the -f operator, as shown in Theo's helpful answer.

This answer compares and contrasts these two approaches.

mklement0
  • 382,024
  • 64
  • 607
  • 775
0

Or use the -f Format operator:

$name = 'Lukas'
Add-Content -Path 'C:\MyPowerShell.txt' -Value ('$myNewVariable = "{0}"' -f $name)
Theo
  • 57,719
  • 8
  • 24
  • 41