Powershell: problem with & in script block

I am facing a problem when running 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 

The problem does not appear if I do not use the variable $x

 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 
+4
source share
2 answers

Variables in a PowerShell session are not migrated to sessions created using Invoke-Command

You need to use the -ArgumentList parameter to send the variables of your command, and then use the $args array to access them in a script block so that your command looks like this:

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

If you are working with variables inside a script block, you need to add a using: modifier. Otherwise, Powershell will look for the var definition inside the script block.

You can use it also using splatting technique. For instance:. @using:params

Like this:

 # C:\Temp\Nested.ps1 [CmdletBinding()] Param( [Parameter(Mandatory=$true)] [String]$Msg ) Write-Host ("Nested Message: {0}" -f $Msg) 

 # C:\Temp\Controller.ps1 $ScriptPath = "C:\Temp\Nested.ps1" $params = @{ Msg = "Foobar" } $JobContent= { & $using:ScriptPath @using:params } Invoke-Command -ScriptBlock $JobContent -ComputerName 'localhost' 
+1
source

Source: https://habr.com/ru/post/1493655/


All Articles