How to Pass variables to remote commands using scriptBlock

Hello Experts,

I am running below code to accept some input from a text file from on SERVER1 and want to execute some set of commands against Server2 using script block and use the same variables defined on server1

$argsArray = @( Get-Content -Path C:\Temp\File.txt )

$Session = New-PSSession -ComputerName server.contoso.local
Invoke-Command -Session $Session -Argumentlist $argsArray -ScriptBlock {

$argsArray[0]
$argsArray[1]
$argsArray[2]
$argsArray[3]

}

 

Error:

Cannot index into a null array.

  • CategoryInfo : InvalidOperation: (:slight_smile: , RuntimeException
  • FullyQualifiedErrorId : NullArray
  • PSComputerName : vmm.contoso.local

Cannot index into a null array.

  • CategoryInfo : InvalidOperation: (:slight_smile: , RuntimeException
  • FullyQualifiedErrorId : NullArray
  • PSComputerName : vmm.contoso.local

Cannot index into a null array.

  • CategoryInfo : InvalidOperation: (:slight_smile: , RuntimeException
  • FullyQualifiedErrorId : NullArray
  • PSComputerName : vmm.contoso.local

Cannot index into a null array.

  • CategoryInfo : InvalidOperation: (:slight_smile: , RuntimeException
  • FullyQualifiedErrorId : NullArray
  • PSComputerName : vmm.contoso.local

 

How do i make sure that the variable which is imported from text file can be used inside the scriptblock running on remote server.

 

Thanks

# Works with PowerShell version 3.0 or higher
$argsArray = @( Get-Content -Path C:\Temp\File.txt )

$Session = New-PSSession -ComputerName server.contoso.local
Invoke-Command -Session $Session -ScriptBlock {

$file = $Using:argsArray ; $file[0]
$file[1] ; $file[2]
}
# Works with PowerShell version 2.0 or higher
$argsArray = @( Get-Content -Path C:\Temp\File.txt )

$Session = New-PSSession -ComputerName server.contoso.local
Invoke-Command -Session $Session -Argumentlist $argsArray -ScriptBlock {
Param($file)
$file[0] ; $file[1] ; $file[2]
}

[quote quote=191557][/quote]

I tried below code but it is only showing part of the first in the text file:

 

$argsArray = @( Get-Content -Path C:\Temp\File.txt )

$Session = New-PSSession -ComputerName vmm.contoso.local
Invoke-Command -Session $Session -Argumentlist $argsArray -ScriptBlock {
Param($file)
$file[0] ; $file[1] ; $file[2]
}

 

Output:

F
i
n

 

The file contains below text:

FinalTest
Gold
ServiceTemplate
contoso.local

Arrays don’t work well with invoke-command or jobs. You have to jump through some hoops. Using: works better.

$argsarray = 1,2,3
start-job { $using:argsarray.count } -args $argsarray | receive-job -wait -auto  

3


start-job { param ($myargs) $myargs.count } -args (,$argsarray) | receive-job -wait -auto

3

Even start-threadjob in PS 6 has this problem, and it doesn’t serialize objects like start-job or invoke-command:

$argsarray = 1,2,3
start-threadjob { param ($myargs) $myargs.count } -argumentlist $argsarray | receive-job -wait -auto 

1