1

I'm trying to run a script that while it runs it will also create a new script. The second script in the end should include those lines:

$line1 = 'some string' 
$line2 = 'some string'
Start-Process $line1 -Arguments $line2

I've tried passing it from the 1st script using the code:

$lines = "$line1 = 'some string'", "$line2 = 'some string'"
foreach ($line in $lines) | Add-Content -Path script2

Which does not works since the var parts are dropped and I'm left with the '= some string' only.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Tomer Leibovich
  • 313
  • 5
  • 17

1 Answers1

0

PowerShell expands variables inside double-quoted strings. Since $line1 and $line2 are undefined in your second code snippet they're expanded to empty strings. Either escape the $ characters with backticks:

$lines = "`$line1 = 'some string'", "`$line2 = 'some string'"

or use single quotes as the outer and double quotes as the inner quotes (variables aren't expanded in single-quoted strings):

$lines = '$line1 = "some string"', '$line2 = "some string"'

I would recommend using a here-string instead of a string array for defining code snippets in code, though, as that improves readability:

$lines = @'
$line1 = "some string"
$line2 = "some string"
'@

Also, foreach ($line in $lines) | Add-Content does not work and will throw an error, because foreach loops don't write to the pipeline, so Add-Content doesn't get any input. Just pipe $lines directly into Add-Content:

$lines | Add-Content 'C:\output.ps1'
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328