All,
Newbie to Powershell but finding really helpfull of using this automation.
I have the following PS script
$remotesession = New-PSSession -ComputerName xxxxxxx
$filepath = ‘c:\ps\DCS\dispatch.vbs’
$quiesc = ‘task’
$scriptBlock = {
param ($filepath, $quiesc)
Start-Process -FilePath $filepath -ArgumentList {$quiesc}
}
invoke-Command -Session $remotesession -ScriptBlock $scriptBlock -ArgumentList {$filepath,$quiesc}
Remove-PSSession -Session $remotesession
When i execute the above command, on my remote computer i cannot see the value of $quiesc getting replaced with the value of Task.
What am i doing wrong here ?
Regards,
Vinod
Hi Vinod,
I think you’ll find that the scriptblock does not have visibility of the variables concerned. You can reference the variables by either using $using:variablename (e.g. $using:quiesc) . Note thats from PowerShell 3.0 and above.
Alternatively, you are able to also reference the variables via $args[0] to reference the first value passed into the scriptblock from the argument list, $args[1] the second and so on. Both of these will not require the param… part.
Here’s an example of your same code
$remotesession = New-PSSession -ComputerName $env:COMPUTERNAME
$filepath = 'c:\ps\DCS\dispatch.vbs'
$quiesc = 'task'
$scriptBlock = {
Write-Output -InputObject "Command to be executed : Start-Process -FilePath $using:filepath -ArgumentList $using:quiesc"
Start-Process -FilePath $using:filepath -ArgumentList $using:quiesc
}
Invoke-Command -Session $remotesession -ScriptBlock $scriptBlock
Remove-PSSession -Session $remotesession
And output :
Command to be executed : Start-Process -FilePath c:\ps\DCS\dispatch.vbs -ArgumentList task
how about running the code without the extra braces:
$filepath = 'c:\ps\DCS\dispatch.vbs'
$quiesc = 'task'
$scriptBlock = {
param ($filepath, $quiesc)
Start-Process -FilePath $filepath -ArgumentList $quiesc
}
invoke-Command -Session $remotesession -ScriptBlock $scriptBlock -ArgumentList $filepath,$quiesc