1

I have syntax similar to the below in PowerShell:

param($1,$2,$3,$4)
$Session = New-PSSession -ComputerName $1
$scriptblock = $ExecutionContext.InvokeCommand.NewScriptBlock("cmd /c $2 $3 $4")
Invoke-Command -Session $Session -ScriptBlock $scriptblock

Where $2 is a .bat and $3 & $4 are arguments I want to pass to the executable. If I run it without arguments I can run the .bat but when I add in the arguments it fails. What am I doing wrong?

I am calling the above by running this in PowerShell:

-ExecutionPolicy Bypass -F "powershellscript for the above" -1 "value" -2 "value" -3 "value" -4 "value"
4
  • "but when I add in the arguments it fails." - how do you add the arguments, and how does it fail (please share any errors thrown, in full)? Commented Nov 12, 2020 at 12:35
  • Added some more information about how I'm calling it. The error thrown is invalid batch file. Commented Nov 12, 2020 at 12:38
  • sounds like everything is working, except cmd on the remote machine might not be able to find the batch file on the remote machine - the argument you pass as -2, is it a fully rooted path? Does it have spaces in it? To verify that the local PowerShell bits are working, try replacing the Invoke-Command statement with Write-Host "About to execute { $sriptblock } against $1" Commented Nov 12, 2020 at 12:44
  • Ok thanks let me try and I'll confirm back Commented Nov 12, 2020 at 12:51

1 Answer 1

2

To use local variables inside remote session, you must prefix them with $Using: scope modifier.

Try this:

param($1,$2,$3,$4)
$Session = New-PSSession -ComputerName $1
$scriptblock = $ExecutionContext.InvokeCommand.NewScriptBlock({ cmd /c $Using:2 $Using:3 $Using:4 })
Invoke-Command -Session $Session -ScriptBlock $scriptblock
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.