windowspowershellwindows-scripting

How to close other PowerShell windows from script


I have a PowerShell script which has the following steps:

  1. Opens another PowerShell window
  2. Navigates to an angular projects directory
  3. Runs a command to serve the project

Is there a way that I can close all other running PowerShell windows, but keep the currently running script and it's newly created window open? Following the changes, I would like it to behave like this:

  1. Close all other PowerShell windows
  2. Opens another PowerShell window
  3. Navigates to an angular projects directory
  4. Runs a command to serve the project

Solution

  • You could use Get-Process to enumerate all running powershell processes, then filter out the current one by comparing with the value of $PID, before piping the rest to Stop-Process:

    Get-Process powershell |? Id -ne $PID |Stop-Process -Force
    

    You can include the child process by ID if necessary:

    $childProcess = Start-Process powershell $childProcArgs -PassThru
    Get-Process powershell |? Id -notin @($PID;$childProcess.Id) |Stop-Process -Force
    

    ... although I would suggest simply killing all other powershell instances first, and then launch the child process after