Skip to content

Instantly share code, notes, and snippets.

@ErhardRainer
Created November 14, 2023 11:04

Revisions

  1. ErhardRainer created this gist Nov 14, 2023.
    39 changes: 39 additions & 0 deletions CloseWindowByTitle.ps1
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,39 @@
    Function CloseWindowByTitle([string]$TitleContains, [bool]$isExplorer, [bool]$isProgram) {
    if ($isExplorer -eq $null) {
    $isExplorer = $true
    }
    if ($isProgram -eq $null) {
    $isExplorer = $true
    }

    if ($isProgram -eq $true)
    {
    Write-Host "Check for running Programs '$TitleContains'"
    #All Processes
    Get-Process | ForEach-Object {
    $WindowName = $_.MainWindowTitle
    if ((($WindowName).Trim()).length -ne 0) {
    if ($WindowName.Contains($TitleContains)) {
    Write-Host "'$WindowName' wird geschlossen"
    Stop-Process $_.ID
    }
    }
    }
    }

    if ($isExplorer -eq $true)
    {
    Write-Host "Check for running Explorer '$TitleContains'"
    #All Shell Applications
    $Applications = (New-Object -comObject Shell.Application).Windows()
    $Applications | ForEach-Object {
    $WindowName = $_.LocationName
    if ($WindowName.Contains($TitleContains)) {
    Write-Host "'$WindowName' wird geschlossen"
    $_.Quit()
    }
    }
    }
    }

    CloseWindowByTitle -TitleContains "Command Prompt" -isExplorer $true -isProgram $false