Execute program on remote computer using PowerShell

How can I execute a program on a remote machine using powershell?


Solution 1:

The cool new way to do this is with WinRM. I've seen this demo'd on Windows Server 2008 R2, although there is a download with powershell v2 & WinRM for other windows operating systems.

The not so cool (or new) way to do this is to use psexec, which isn't powershell, but I'm sure there's some way to invoke it via powershell-esque syntax.

Solution 2:

You could also use WMI and remotely start a process. It won't be interactive and you'll have to trust that it will end on its own. This doesn't require anything on the remote computer other than open ports for WMI.

Function New-RemoteProcess {
    Param([string]$computername=$env:computername,
        [string]$cmd=$(Throw "You must enter the full path to the command which will create the process.")
    )

    $ErrorActionPreference="SilentlyContinue"

    Trap {
        Write-Warning "There was an error connecting to the remote computer or creating the process"
        Continue
    }    

    Write-Host "Connecting to $computername" -ForegroundColor CYAN
    Write-Host "Process to create is $cmd" -ForegroundColor CYAN

    [wmiclass]$wmi="\\$computername\root\cimv2:win32_process"

    #bail out if the object didn't get created
    if (!$wmi) {return}

    $remote=$wmi.Create($cmd)

    if ($remote.returnvalue -eq 0) {
        Write-Host "Successfully launched $cmd on $computername with a process id of" $remote.processid -ForegroundColor GREEN
    }
    else {
        Write-Host "Failed to launch $cmd on $computername. ReturnValue is" $remote.ReturnValue -ForegroundColor RED
    }
}

Sample usage:

New-RemoteProcess -comp "puck" -cmd "c:\windows\notepad.exe"

Solution 3:

Here's the psexec/powershell link.

Solution 4:

Interesting enough I used this to run notepad on a remote computer and it didn't appear. I checked the Task manager and the process ID that the call returned was indeed there!

Windows stated that this was a security concept and the process would run hidden/ or in the background!