forked from fleschutz/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
close-program.ps1
executable file
·58 lines (55 loc) · 1.68 KB
/
close-program.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<#
.SYNOPSIS
Closes a program
.DESCRIPTION
This PowerShell script closes a program's processes gracefully.
.PARAMETER fullProgramName
Specifies the full program name
.PARAMETER programName
Specifies the program name
.PARAMETER programAliasName
Specifies the program alias name
.EXAMPLE
PS> ./close-program "Google Chrome" "chrome.exe"
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
Author: Markus Fleschutz | License: CC0
#>
param([string]$fullProgramName = "", [string]$programName = "", [string]$programAliasName = "")
try {
if ($programName -eq "") {
Get-Process | where-object {$_.mainWindowTitle} | format-table Id, Name, mainWindowtitle -AutoSize
$programName = Read-Host "Enter the program name"
}
if ($fullProgramName -eq "") {
$fullProgramName = $programName
}
$processes = Get-Process -name $programName -errorAction 'silentlycontinue'
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) {
throw "$fullProgramName isn't running"
}
foreach ($process in $processes) {
$_.CloseMainWindow() | Out-Null
}
Start-Sleep -milliseconds 100
Stop-Process -name $programName -force -errorAction 'silentlycontinue'
}
if ($($processes.Count) -eq 1) {
"✅ $fullProgramName closed."
} else {
"✅ $fullProgramName closed and $($processes.Count) processes stopped."
}
exit 0 # success
} catch {
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}