1

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:

enter image description here

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)?!?

Fredster
  • 97
  • 1
  • 3
  • 11
  • I see what you mean, the added character value 8 in front of the server1 name... Where the heck did that come from, lol! Thanks for your help: I never would have found that (As it is not visible at all in the ISE! – Fredster Jan 27 '17 at 22:57
  • character value 8, that's a [backspace](http://www.asciitable.com/) - how do you accidentally get that in a string? – TessellatingHeckler Jan 27 '17 at 23:12
  • I have no idea whatsoever: I've been struggling with this for several days... Only after pasting it I found the odd character... – Fredster Jan 27 '17 at 23:16

1 Answers1

3

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.

mklement0
  • 382,024
  • 64
  • 607
  • 775