PowerShell/Scripts/close-program.ps1

59 lines
1.7 KiB
PowerShell
Raw Normal View History

2021-09-27 10:38:12 +02:00
<#
2021-07-13 21:10:02 +02:00
.SYNOPSIS
2021-10-16 16:50:10 +02:00
Closes a program's processes
2021-10-04 21:29:23 +02:00
.DESCRIPTION
2022-01-29 12:47:46 +01:00
This PowerShell script closes a program's processes gracefully.
2021-10-16 16:50:10 +02:00
.PARAMETER FullProgramName
Specifies the full program name
.PARAMETER ProgramName
Specifies the program name
.PARAMETER ProgramAliasName
Specifies the program alias name
2021-07-13 21:10:02 +02:00
.EXAMPLE
2021-09-24 17:19:49 +02:00
PS> ./close-program "Google Chrome" "chrome.exe"
2021-07-13 21:10:02 +02:00
.LINK
https://github.com/fleschutz/PowerShell
2022-01-29 12:47:46 +01:00
.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 {
$Processes = get-process -name $ProgramAliasName -errorAction 'silentlycontinue'
if ($Processes.Count -eq 0) {
2021-11-29 16:25:01 +01:00
throw "$FullProgramName isn't running"
2021-02-13 16:36:47 +01:00
}
foreach ($Process in $Processes) {
$_.CloseMainWindow() | Out-Null
}
start-sleep -milliseconds 100
stop-process -name $ProgramName -force -errorAction 'silentlycontinue'
}
2021-10-21 15:52:34 +02:00
if ($($Processes.Count) -eq 1) {
2021-10-21 17:02:43 +02:00
"✔️ $FullProgramName closed, 1 process stopped"
2021-10-21 15:52:34 +02:00
} else {
2021-10-21 17:02:43 +02:00
"✔️ $FullProgramName closed, $($Processes.Count) processes stopped"
2021-10-21 15:52:34 +02:00
}
2021-09-27 10:09:45 +02:00
exit 0 # success
} catch {
2022-04-13 12:06:32 +02:00
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}