2020-12-27 11:02:20 +01:00
|
|
|
#!/snap/bin/powershell
|
|
|
|
|
|
|
|
# Syntax: ./close-program.ps1 [<program-name>]
|
|
|
|
# Description: closes the given program gracefully
|
|
|
|
# Author: Markus Fleschutz
|
|
|
|
# Source: github.com/fleschutz/PowerShell
|
|
|
|
# License: CC0
|
|
|
|
|
|
|
|
param([string]$ProgramName)
|
|
|
|
|
|
|
|
try {
|
|
|
|
if ($ProgramName -eq "" ) {
|
|
|
|
Get-Process | Where-Object {$_.mainWindowTitle} | Format-Table Id, Name, mainWindowtitle -AutoSize
|
|
|
|
$ProgramName = read-host "Enter program to close"
|
|
|
|
}
|
2020-12-28 10:23:17 +01:00
|
|
|
|
|
|
|
$Processes = Get-Process -name $ProgramName -erroraction 'silentlycontinue'
|
|
|
|
foreach ($Process in $Processes) {
|
2020-12-28 09:40:26 +01:00
|
|
|
$_.CloseMainWindow() | Out-Null
|
2020-12-28 10:23:17 +01:00
|
|
|
}
|
|
|
|
start-sleep -milliseconds 100
|
|
|
|
Stop-Process -name $ProgramName -force -erroraction 'silentlycontinue'
|
|
|
|
|
|
|
|
$ProcessCount = $Processes.Count
|
|
|
|
if ($ProcessCount -eq 0) {
|
2020-12-28 09:40:26 +01:00
|
|
|
throw "program '$ProgramName' is not started yet"
|
2020-12-27 11:02:20 +01:00
|
|
|
}
|
2020-12-28 10:23:17 +01:00
|
|
|
write-output "OK - program '$ProgramName' with $ProcessCount process(es) has been closed."
|
2020-12-28 09:40:26 +01:00
|
|
|
exit 0
|
2020-12-27 11:02:20 +01:00
|
|
|
} catch {
|
|
|
|
write-error "ERROR in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
|
|
|
|
exit 1
|
|
|
|
}
|