#requires -Version 5 classAppInstance : System.Diagnostics.Process { # Constructor, being called when you instantiate a new object of # this class AppInstance([string]$Name) : base() { # launch the process, get a regular process object, and then # enhance it with additional functionality $this.StartInfo.FileName = $Name $this.Start() $this.WaitForInputIdle() }
# for example, rename an existing method [void]Stop() { $this.Kill() }
# or invent new functionality # Close() closes the window gracefully. Unlike Kill(), # the user gets the chance to save unsaved work for # a specified number of seconds before the process # is killed [void]Close([Int]$Timeout = 0) { # send close message $this.CloseMainWindow() # wait for success if ($Timeout-gt0) { $null = $this.WaitForExit($Timeout * 1000) } # if process still runs (user aborted request), kill forcefully if ($this.HasExited -eq$false) { $this.Stop() } }
# example of how to change a property like process priority [void]SetPriority([System.Diagnostics.ProcessPriorityClass] $Priority) { $this.PriorityClass = $Priority }
[System.Diagnostics.ProcessPriorityClass]GetPriority() { if ($this.HasExited -eq$false) { return$this.PriorityClass } else { Throw"Process PID $($this.Id) does not run anymore." } }
# add static methods, for example a way to list all processes # variant A: no arguments static[System.Diagnostics.Process[]] GetAllProcesses() { return [AppInstance]::GetAllProcesses($false) } # variant B: submit $false to see only processes that have a window static[System.Diagnostics.Process[]] GetAllProcesses([bool]$All) { if ($All) { returnGet-Process } else { returnGet-Process | Where-Object { $_.MainWindowHandle -ne0 } } } }
# you can always run static methods [AppInstance]::GetAllProcesses($true) | Out-GridView-Title'All Processes' [AppInstance]::GetAllProcesses($false) | Out-GridView-Title'Processes with Window'
# this is how you instantiate a new process and get back # a new enhanced process object # classic way: # $notepad = New-Object -TypeName AppInstance('notepad') # new (and faster) way in PowerShell 5 to instantiate new objects: $notepad = [AppInstance]::new('notepad')
# set a different process priority $notepad.SetPriority('BelowNormal')
# add some text to the editor to see the close message Start-Sleep-Seconds5
# close the application and offer to save changes for a maximum # of 10 seconds $notepad.Close(10)