I have a PowerShell (v2) script, that I want to be able to call itself, but have that second invocation run on a remote computer. I need to be able to pass several (~10) named parameters to the second invocation.
In the past, when working with jobs, I've used "splatting" to create a hashmap of values and pass them along to the job. I've tried something similar with Invoke-Command, but it isn't working as expected. I created a simple script to illustrate my point, save this as test.ps1. If not the remote machine, print the variables, and call the remote invocation, the remote invocation just prints what it received.
param([string]$paramA, [string]$paramB, [bool]$remote = $false)
if(!$remote)
{
Write-Host "LOCAL: paramA is $paramA"
Write-Host "LOCAL: paramB is $paramB"
Write-Host "LOCAL: remote is $remote"
}
else
{
Write-Host "REMOTE: paramA is $paramA"
Write-Host "REMOTE: paramB is $paramB"
Write-Host "REMOTE: remote is $remote"
}
if(!$remote)
{
$sess = New-PSSession -computername MACHINENAME -credential CREDENTIALS
#w/o hashmap
$responseObject = Invoke-Command -session $sess -FilePath .\test.ps1 -ArgumentList($paramA,$paramB,$true) -AsJob
#with hashmap (this doesn't work)
#$arguments = @{paramA = $paramA; paramB = $paramB; remote = $true}
#$responseObject = Invoke-Command -session $sess -FilePath .\test.ps1 -ArgumentList $arguments -AsJob
while($responseObject.State -ne "Completed")
{
}
$result = Receive-Job -Id $responseObject.Id
Write-Host $result
Remove-PSSession -Session $sess
}
Running the script I would see this, but uncommenting the hashmap part fails (never returns).
.\test.ps1 -paramA "First" -paramB "Second"
LOCAL: paramA is First
LOCAL: paramB is Second
LOCAL: remote is False
REMOTE: paramA is First
REMOTE: paramB is Second
REMOTE: remote is True
I've tried variations of this with scriptblocks, etc, but I'm missing something.