Skip to content

Instantly share code, notes, and snippets.

@santisq
Last active December 5, 2024 16:38
Show Gist options
  • Save santisq/f28fa0e8e61c14c15197804dadf5a930 to your computer and use it in GitHub Desktop.
Save santisq/f28fa0e8e61c14c15197804dadf5a930 to your computer and use it in GitHub Desktop.
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