PowerShell/Scripts/close-program.ps1

50 lines
1.5 KiB
PowerShell
Raw Normal View History

2021-04-21 19:53:52 +02:00
<#
2021-07-13 21:10:02 +02:00
.SYNOPSIS
close-program.ps1 [<full-program-name>] [<program-name>] [<program-alias-name>]
.DESCRIPTION
Closes the processes of the given program gracefully
.EXAMPLE
PS> .\close-program.ps1 "Google Chrome" "chrome.exe"
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz / License: CC0
2020-12-29 15:14:21 +01:00
#>
2021-07-15 15:51:22 +02:00
param([string]$FullProgramName = "", [string]$ProgramName = "", [string]$ProgramAliasName = "")
2021-02-18 20:17:55 +01:00
try {
2021-07-15 15:51:22 +02:00
if ($ProgramName -eq "") {
get-process | where-object {$_.mainWindowTitle} | format-table Id, Name, mainWindowtitle -AutoSize
$ProgramName = read-host "Enter program name"
}
if ($FullProgramName -eq "") {
$FullProgramName = $ProgramName
}
2020-12-29 16:28:03 +01:00
$Processes = get-process -name $ProgramName -errorAction 'silentlycontinue'
2021-02-13 16:36:47 +01:00
if ($Processes.Count -ne 0) {
foreach ($Process in $Processes) {
$Process.CloseMainWindow() | Out-Null
}
start-sleep -milliseconds 100
stop-process -name $ProgramName -force -errorAction 'silentlycontinue'
} else {
2021-02-13 16:36:47 +01:00
$Processes = get-process -name $ProgramAliasName -errorAction 'silentlycontinue'
if ($Processes.Count -eq 0) {
throw "$FullProgramName is not started yet"
}
foreach ($Process in $Processes) {
$_.CloseMainWindow() | Out-Null
}
start-sleep -milliseconds 100
stop-process -name $ProgramName -force -errorAction 'silentlycontinue'
}
2021-04-16 20:01:38 +02:00
write-host -foregroundColor green "✔️ closed $FullProgramName, found ($($Processes.Count) process(es)"
exit 0
} catch {
2021-05-02 21:30:48 +02:00
write-error "⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}