1

I need to execute a Powershell script on a remote machine from a local script. Problem is, I don't know the path or filename of the remote script until runitime.

I've tried the following line in my local script:

Invoke-Command -ComputerName $TargetServer -ScriptBlock { & ($TargetMSI) '$MSI' 'C:\Program Files (x86)\Vasanta.Int.MIS' 'Dev' }

Problem is this returns the error: The expression after '&' in a pipeline element produced an invalid object.

If replace the $TargetMSI with a hard-coded string literal then it works fine.

Can anyone please tell me what I need to change?

1 Answer 1

2

When you Invoke-Command in v2 there is no direct way to pass variables to scriptblock. You need to use -ArgumentList + param () in scriptblock combo:

Invoke-Command -ScriptBlock { param ($TargetMSI, $MSI) & $TargetMSI '$MSI' } -ArgumentList $TargetMSI, $MSI

this is fixed/ improved in v3 with $using:localvariable syntax.

Sign up to request clarification or add additional context in comments.

1 Comment

Great, thanks Batek. My working line of code now looks as follows: Invoke-Command -ComputerName $TargetServer -ScriptBlock {param ($TargetMSI, $MSI, $InstallPath, $Environment) & $TargetMSI $MSI $InstallPath $Environment} -ArgumentList $TargetMSI, $MSI, $InstallPath, $Environment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.