Search code examples
powershellprocesswindow

Manipulating a process' main window in powershell


I've been trying to create a script for myself that will allow me to open several programs at once, but in a non-invasive fashion. One program for example, Steam, doesn't always need to be started up when I boot my computer so I want to script it along with origin / gtalk / whatever that will open the programs, but close the main windows of specific programs (steam / origin, I just use my start menu or taskbar to start games).

Now doing my research it doesn't seem overly complicated to do just that.

get-process steam, origin | where {$_.closeMainWindow()}

I'm okay with this, I can have it run multiple times, but I thought I would try my hand at making it a bit more fancy. With steam, and Origin, there are several windows that are considered the main title window that the command closes. The command however only closes one at a time so it would have to be run multiple times to close them. My idea is to create a function that has a while operator.

This doesn't quite work because I'm pretty new to all the concepts / features of powershell so I don't quite know if there's another, easier way to do this. I'm not even sure if this is a valid while loop considering the condition isn't being compared to anything, I tried making it -eq $true like this while ((get-process steam, origin | where {$_.mainWindowTitle}) -eq $true) but got errors.

function test {
    while (get-process steam, origin | where {$_.mainWindowTitle}) {
        $_.closeMainWindow;
    }
}

output being passed to the third line is:

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName                 
-------  ------    -----      ----- -----   ------     -- -----------                 
   1161      97    97776     123000   334     3.62   4468 Origin                      
    570      73   175252      58392   484    10.65   1484 Steam  

Kind of a silly thing to ask help for, it's not an extremely valuable script to have but I think it's cool :P


Solution

  • I just don't understand why you don't simply stop the process using :

    Get-Process steam,origin -ErrorAction silentlycontinue | stop-process
    

    But you can use this :

    while (($p=Get-Process steam,origin -ErrorAction silentlycontinue) -ne $null)
    {
      $p | % {$_.CloseMainWindow()}
    }