How to Run a Cmd Through Invoke-Command
$Remoteinst = "\Windows\Temp\Myfolder" $Remotecomp = Computername $Remotesess = New-Pssession $Remotecomp $Remotedir = "C:" + $Remoteinst + "\Install. Cmd"...
$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.
2 Answers
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 theusingscope:$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 }
Add cmd /c to the front of the path to the batch file.