Skip to content

Commit d48addb

Browse files
jborean93sdwheeler
andauthored
Add PipelineStopToken documentation (#11950)
* Add PipelineStopToken documentation Adds the documentation for the new PipelineStopToken property on $PSCmdlet. This property is used to remove boilerplate currently needed for invoking async methods in PowerShell functions. * Editorial update * Update PipelineStopToken description and example --------- Co-authored-by: Sean Wheeler <[email protected]>
1 parent d0bf370 commit d48addb

File tree

1 file changed

+34
-1
lines changed

1 file changed

+34
-1
lines changed

reference/7.6/Microsoft.PowerShell.Core/About/about_Functions_Advanced.md

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
description: Introduces advanced functions that are a way to create cmdlets using scripts.
33
Locale: en-US
4-
ms.date: 01/02/2025
4+
ms.date: 03/25/2025
55
online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_functions_advanced?view=powershell-7.6&WT.mc_id=ps-gethelp
66
schema: 2.0.0
77
title: about_Functions_Advanced
@@ -69,6 +69,38 @@ Advanced functions differ from compiled cmdlets in the following ways:
6969
named parameters.
7070
- Advanced functions can't be used in transactions.
7171

72+
## PipelineStopToken
73+
74+
Beginning with PowerShell 7.6-preview.4, `$PSCmdlet` includes the
75+
`PipelineStopToken` property allowing access a [CancellationToken][07] tied to
76+
the PowerShell stop event source. The token is triggered when the PowerShell
77+
pipeline receives a request to stop. Use it with a .NET method that accepts a
78+
`CancellationToken` overload to exit the method when requested rather than
79+
waiting until the method returns.
80+
81+
In the following example, the function is calling `HttpClient.GetStringAsync`,
82+
which can take time to respond when the network is slow or there is a lot of
83+
data being returned.
84+
85+
```powershell
86+
function Invoke-CancelableWebRequest {
87+
[CmdletBinding()]
88+
param(
89+
[Parameter(Mandatory=$true)]
90+
[string]
91+
$Url
92+
)
93+
94+
$client = [System.Net.Http.HttpClient]::new()
95+
$client.GetStringAsync(
96+
$Url,
97+
$PSCmdlet.PipelineStopToken).GetAwaiter().GetResult()
98+
}
99+
100+
Invoke-CancelableWebRequest -Url https://httpbin.org/delay/10
101+
# Press ctrl+c to cancel
102+
```
103+
72104
## See also
73105

74106
- [about_Functions][05]
@@ -85,3 +117,4 @@ Advanced functions differ from compiled cmdlets in the following ways:
85117
[04]: about_Functions_OutputTypeAttribute.md
86118
[05]: about_Functions.md
87119
[06]: about_Variables.md
120+
[07]: xref:System.Threading.CancellationToken

0 commit comments

Comments
 (0)