I am trying to create a dynamic scriptblock, so I can use variables in the scriptblock.
This is my code:
$Servers = "server1", "server2"
$Command = "c:\plink -t user@" + $Servers[0] + " -pw 'password'"
$Command = [Scriptblock]::Create($Command)
$Command2 = {c:\plink -t user@server1 -pw 'password'}
$command
$command2
Running the script in the PowerShell ISE produces, what I would expect:
c:\plink -t user@server1 -pw 'password'
c:\plink -t user@server1 -pw 'password'
Both $command and $command2 present identical output, and both are valid scriptblocks when checked with Get-Member -Verbose.
My problem is that executing the first line produces a connection error, where the identical output from $command2 works just fine and connects to the server.
Looking into the issue, I found that copy/pasting the two produced lines in the output window of the ISE to a Notepad reveals the problem:
As you can see in the JPG, an odd character is added, right after the '@' sign, which causes the command to fail...
Any idea why this happens (and how I can solve it)?!?
Based on @Fredster's feedback:
It turns out that an invisible control character had crept into this assignment statement:
$Servers = "server1", "server2"
By using $Servers[0]
to build the string that was later converted to a script block, that control character became an invisible part of the script block and caused problems on invocation.
To diagnose such problems, pipe values to the Format-Hex
cmdlet (PSv5+), which will show every character that makes up a string, including normally invisible ones.
Caveat: By default, only characters in the ASCII range are shown correctly; any others are simply represented as literal ?
- use the -Encoding
parameter as needed.