I need help with parameter passing using Invoke-Command within a PSSession. I have a program on a remote computer that I need to execute and this program requires to have some parameter inputs.
Some of these parameters have spaces in them. I have tried to create the script block as shown below and use the Invoke-Command cmdlet to invoke this program withing a PSSession, but it complains about the -p parameter being ambiguous.
Parameter cannot be processed because the parameter name ‘p’ is ambiguous. Possible matches include: -PassThru -FilePath.
+ CategoryInfo : InvalidArgument: ( [Start-Process], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameter,Microsoft.PowerShell.Commands.StartProcessCommand
How can get around this -p ambiguous error and get this invoke command to work?
Instead of trying to use [scriptblock]::Create() to pass “parameters”, just use actual parameters. There are two ways you can do this, depending on whether you’re using PowerShell 3.0 or later on both sides of the connection:
# The easier PowerShell 3.0 way, the $using: scope modifier:
Invoke-Command -ComputerName $computer -ScriptBlock {
Start-Process D:\Application\app.exe -ArgumentList -i $using:RemoteInstance -j "$using:RemoteJob" -d $using:SQLDomain -t $using:timeLimit -p $using:RunMode
}
# The PowerShell 2.0-compatible way, using the -ArgumentList parameter of Invoke-Command. These parameters are passed by position,
# so make sure the order you use in the -ArgumentList parameter matches the order in the script block's parameters.
$scriptBlock = {
param ($RemoteInstance, $RemoteJob, $SQLDomain, $timeLimit, $RunMode)
Start-Process D:\Application\app.exe -ArgumentList -i $RemoteInstance -j "$RemoteJob" -d $SQLDomain -t $timeLimit -p $RunMode
}
Invoke-Command -ComputerName $computer -ScriptBlock $scriptBlock -ArgumentList ($RemoteInstance, $RemoteJob, $SQLDomain, $timeLimit, $RunMode)
Oh, missed that part. The -ArgumentList parameter to Start-Process takes an array of strings (though you can do just a single string if you prefer); you need to quote your stuff there so PowerShell doesn’t try to interpret those -i, -j, etc as PowerShell parameters to the Start-Process command. Try this:
One more thing. Currently, the program path for the Start-Process cmdlet in the script block is hard coded in the script.
Is there a way to pass the program path as a parameter to the script block? I tried to set the program path to a variable, and placed the variable in in the script block, and it complained that it could not find the program file.
Sure, no different than passing in all the other variables to the command. You just have to add it to both your param block and the -ArgumentList parameter when calling Invoke-Command.
It looks like I can pass another positional parameter to the from the Invoke-Command cmdlet to the Start-Process cmdl within the script block, and works fine.