0

this code works as expected:

$var = "a123"
$script = @'
Add-Content C:\temp\test.txt -Value {{"{0}     name1"}}
Add-Content C:\temp\test.txt -Value {{"{0}     name2"}}
'@ -f $var
$command = [scriptblock]::Create($script)
Start-Process powershell.exe -Verb RunAs -ArgumentList "-NoExit -command & {$command}" -Wait

But when I change the value of $var to "123", I get the error:

At line:1 char:49
+ & {Add-Content C:\temp\test.txt -Value {123     name1}
+                                                 ~~~~~
Unexpected token 'name1' in expression or statement.
At line:2 char:46
+ Add-Content C:\temp\test.txt -Value {123     name2}}
+                                              ~~~~~
Unexpected token 'name2' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedToken

I tried with other quotes, with casting to string but I have no solution that works. Can anyone help please?

1 Answers1

0

I think I figured out, what is happening and how to work around it.

The problem is, that somehow the double quotes in your script block are lost, once the command is passed to powershell.exe and something funny happens, when the first token of your script block is not identified as a string. Compare this:

{123a     name1} # Returns a script block
{123      name1} # Fails with "UnexpectedToken" exception
{$true    name1} # Fails with "UnexpectedToken" exception

I have not the slightest idea, why that happens, but that is what you can do, to work around it:

$var = "123"
$script = @'
Add-Content C:\temp\test.txt -Value {{'{0}     name1'}}
Add-Content C:\temp\test.txt -Value {{'{0}     name2'}}
'@ -f $var

The single quotes are somehow maintained when the command is passed on and the output in C:\temp\test.txt looks like this:

'123 name1'
'123 name2'
Manuel Batsching
  • 3,406
  • 14
  • 20