Powershell: Issue with & in scriptblock

user2622678 picture user2622678 · Jul 26, 2013 · Viewed 9.3k times · Source

I face an issue when I run the following command

$x =  "c:\Scripts\Log3.ps1"
$remoteMachineName = "172.16.61.51"
Invoke-Command -ComputerName $remoteMachineName  -ScriptBlock {& $x}

The expression after '&' in a pipeline element produced an invalid object. It must result in a command name, script
block or CommandInfo object.
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : BadExpression
    + PSComputerName        : 172.16.61.51

Issue is not seen if I dont use $x variable

Invoke-Command -ComputerName $remoteMachineName  -ScriptBlock {& 'c:\scripts\log3.ps1'}

    Directory: C:\scripts


Mode                LastWriteTime     Length Name                                  PSComputerName
----                -------------     ------ ----                                  --------------
-a---         7/25/2013   9:45 PM          0 new_file2.txt                         172.16.61.51

Answer

Stanley De Boer picture Stanley De Boer · Jul 26, 2013

Variables in your PowerShell session are not transferred to sessions created with Invoke-Command

You need to use the -ArgumentList parameter to send the variables your command and then use the $args array to access them in the script block so your command will look like:

Invoke-Command -ComputerName $remoteMachineName  -ScriptBlock {& $args[0]} -ArgumentList $x