Home » Powershell » NewRemote-Process

NewRemote-Process

cls
Function New-RemoteProcess {
#[CmdletBinding()]
Param(
[String]$ComputerName = $env.computername,
[String]$Cmd = $(Throw “You must enter path to the command which will create the process”),
[String]$ac,
[String]$wait
)
if($PsBoundparameters.containskey(‘Debug’)){ $Debugpreference = “Continue”}
$ErrorActionPreference = “SilentlyContinue”
Trap {
     Write-Warning “There is an error connecting to the remote computer or creating process”
     $_.Exception.Message
     Continue
      }
Write-Debug “Connecting to $ComputerName”
Write-Debug “Process to create is $Cmd”
if( $ac ) {
           Write-Debug “Alternate Credentails required”
           $Cred = Get-Credential
           $remote = Invoke-WmiMethod -ComputerName $Computername -Class Win32_process -Name Create -EnableAllPrivileges $Cmd -Credential $Cred
           if( !$Remote ) {
                          Write-Debug “Could not create remote process”
                          return 32
                          }
           $RPID = $remote.processID
           Write-Debug “Remote process was with Process ID : $RPID”
           if( $wait ) {
                       While( Get-WmiObject -Credential $Cred -ComputerName $Computername -Filter “ProcessID=$RPID”) {
                            Write-Debug ” Waiting on process id $RPID to exit”
                            Start-Sleep -Seconds 2
                             }
                        }
           Write-Debug “Remote Access Exited”
           }
           else {
                 $Remote = Invoke-WmiMethod -ComputerName $Computername -Class Win32_Process -Name Create -EnableAllPrivileges -ArgumentList $Cmd
                 if( !$Remote ){
                               Write-Debug “Could not create remote process. Bailing out”
                               Return 32
                               }
                 $RPID = $Remote.ProcessID
                 Write-Debug “Remote Process was launched with process ID : $RPID”
                 if( $Wait ) {
                             While( Get-WmiObject Win32_process -ComputerName $Computername -Filter “ProcessID=$RPID” ) {
                                   Write-Debug “Waiting on process ID $RPID to exit”
                                   Start-Sleep -Seconds 2
                                   }
                             }
                  Write-Debug “Remote process exited”
                  }
if( $remote.returnvalue -eq 0 ) {
                      Write-Host “Sucessfully launched $cmd on $Computername with a process ID or $RPID”
                      return 0 } else {
                                 Write-Host ” Failed to launch $cmd on $computername. Return value is $($remote.Returnvalue)”
                                 Return 1
                                 }
                      } #function closer

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *
Email *
Website