Interacting with existing process

This topic contains 1 reply, has 2 voices, and was last updated by Profile photo of Max Kozlov Max Kozlov 3 weeks, 3 days ago.

  • Author
    Posts
  • #57382
    Profile photo of Andrew
    Andrew
    Participant

    Greetings all,

    I'm new to Powershell (and scripting in general) and have not had any luck with finding an answer to my question through searching.

    I have a batch file which starts an executable that continually runs in the background. The executable hijacks the command window to allow user input into the window in order to start tasks and cleanly exit the program. I would like to schedule a task that inputs the “Backup” command into the cmd window and preferably waits to receive the “Task Complete” message before continuing with other tasks before exiting.

    I currently have the below code which allows me to start cmd.exe, run the program (I made a simple batch file which mimics the executable called Infinate.bat), and input commands to the program.

    $psi = New-Object System.Diagnostics.ProcessStartInfo;
    $psi.FileName = "cmd.exe"
    $psi.UseShellExecute = $false
    $psi.RedirectStandardInput = $true
    
    $p = [System.Diagnostics.Process]::Start($psi)
    $p.StandardInput.WriteLine("title Infinate") 
    $p.StandardInput.WriteLine("Z:\Infinite.bat")
    
    Start-Sleep -s 2
    $p.StandardInput.WriteLine("Backup")

    What I want to do now is break the input of the Backup command into a new script which I can schedule in the task scheduler (or run as a one off). I have so far been unable to find a way to reattach the StandardInput to a new Powershell instance. I currently find the correct process using the window title but the $process.StandardInput property, while it exists, appears to have a null value. The last line of the below code gives an error of “You cannot call a method on a null-valued expression.”.

    $processes = Get-Process cmd
    
    foreach ( $process in $processes )
    {
        if ( $process.mainWindowTitle -eq "Infinate" )
        {
            $infinateProcess = $process
        }
    }
    
    $infinateProcess.StandardInput.WriteLine("Backup")
  • #57386
    Profile photo of Max Kozlov
    Max Kozlov
    Participant

    Streams are empty because you not the owner of a processes and you not launch it (and thus doesnt fill RedirectStandardInput 🙂 )

    I'm found something that looks like you want (not tested)
    http://stackoverflow.com/questions/5711291/get-the-handle-and-write-to-the-console-that-launched-our-process

You must be logged in to reply to this topic.