Monday, April 14, 2008

New-RemoteProcess

It is possible to initiate a process on a remote machine through PowerShell, but only through WMI.
Unfortunately there are certain limitations to this functionality in WMI:
1.) The process will never be visible to a user logged on to the remote server.
2.) The process will only be initialized - no return values are passed back through WMI.

Limitation #2 can be circumvented by directing the output to a file, and then accessing the file after the process has completed.

Here is a quick example:

Function New-RemoteProcess {
## The function returns two values.
## A returncode (0 = success) and the ProcessID on the target server.
    Param ($target, $command, $path="c:\")
    $p = [WMIClass]"\\$target\ROOT\CIMV2:Win32_Process"
    $inParams = $p.psbase.GetMethodParameters("Create")
    $inparams.commandline = $command
    $inparams.currentdirectory = $path
    $result = $p.psbase.invokemethod("Create", $inparams, $null)
    Write-Output $result.ReturnValue
    Write-Output $result.ProcessID
}

New-RemoteProcess "MyServer.something.com" "Calc.exe"

No comments: