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

3
  • 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! Commented Jan 27, 2017 at 22:57
  • character value 8, that's a backspace - how do you accidentally get that in a string? Commented Jan 27, 2017 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... Commented Jan 27, 2017 at 23:16

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Marked answered! Thanks for your help! This had me boggled for days!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.