Karmaxdw
Karmaxdw

Reputation: 163

How to run a CMD Through Invoke-Command

$remoteinst = "\Windows\Temp\MyFolder"
$remotecomp = ComputerName
$remotesess = New-PSSession $remotecomp
$remotedir = "C:" + $remoteinst + "\Install.cmd"
Invoke-Command -Session $remotesess -ScriptBlock {$remotedir}

I'm trying to run the Install.cmd file on a remote computer. I realised I can't pass commands through Enter-PSSession but I'm struggling to solve this issue.

Upvotes: 0

Views: 19822

Answers (2)

mklement0
mklement0

Reputation: 437062

  • There's no need for creating an explicit session: you can pass the target computer name directly to Invoke-Command -ComputerName <computerName>.

  • Invoking a command whose name / path is stored in a variable requires &, the call operator.

  • The script block passed to Invoke-Command -ComputerName ... is executed remotely, so you cannot directly use local variables in it; in PSv3+, the simplest way to solve this problem is to use the using scope: $using:<localVarName>

Keeping all these points in mind, we get:

$remoteinst = "\Windows\Temp\MyFolder"
$remotecomp = ComputerName # Note: This syntax assumes that `ComputerName` is a *command*
$remotedir = "C:" + $remoteinst + "\Install.cmd"
Invoke-Command -ComputerName $remoteComp -ScriptBlock { & $using:remotedir }

Upvotes: 2

Adam Parsons
Adam Parsons

Reputation: 536

Add cmd /c to the front of the path to the batch file.

Upvotes: 0

Related Questions