Last active
December 5, 2024 16:38
-
-
Save santisq/f28fa0e8e61c14c15197804dadf5a930 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using namespace System.Management.Automation | |
function Stop-PowerShell { | |
param( | |
[Parameter(Mandatory, ValueFromPipeline)] | |
[System.Diagnostics.Process] $Process, | |
[Parameter()] | |
[ValidateRange(1, [int]::MaxValue)] | |
[int] $TimeoutSeconds = 10) | |
process { | |
try { | |
$pipe = [Runspaces.NamedPipeConnectionInfo]::new($Process.Id) | |
$rs = [runspacefactory]::CreateRunspace($pipe) | |
$rs.Open() | |
$ps = [powershell]::Create($rs).AddScript({ | |
Get-Runspace | | |
Where-Object { $_ -ne [runspace]::DefaultRunspace } | | |
ForEach-Object CloseAsync | |
}) | |
$null = $ps.InvokeAsync() | |
if (-not $Process.WaitForExit([timespan]::FromSeconds($TimeoutSeconds))) { | |
$PSCmdlet.WriteError([ErrorRecord]::new( | |
"Failed to stop PowerShell with Process Id '$($Process.Id)'.", | |
'StopFailed', | |
[ErrorCategory]::OperationTimeout, | |
$null)) | |
} | |
} | |
catch { | |
$PSCmdlet.WriteError($_) | |
} | |
finally { | |
${ps}?.Dispose() | |
${rs}?.Dispose() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment