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