Skip to content

Commit f858b4a

Browse files
jborean93sdwheeler
authored andcommitted
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.
1 parent 44c125a commit f858b4a

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

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

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,40 @@ 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, you can access the `PipelineStopToken` property
75+
on the `$PSCmdlet` variable to access a [CancellationToken][07] tied to the
76+
PowerShell stop event source. This token will be automatically triggered when
77+
the PowerShell pipeline has been requested to stop. It is designed to be used
78+
with .NET methods that accept a `CancellationToken` overload so that the
79+
method can exit when requested rather than wait until the method returns from
80+
what it is doing.
81+
82+
A common example is if the function is calling a .NET async compatible API. In
83+
the below example the function is calling `HttpClient.GetStringAsync` which
84+
could take a while to respond if the network is slow or there is a lot of data
85+
being returned.
86+
87+
```powershell
88+
Function Invoke-WebGetRequest {
89+
[CmdletBinding()]
90+
param(
91+
[Parameter(Mandatory=$true)]
92+
[string]
93+
$Url
94+
)
95+
96+
$client = [System.Net.Http.HttpClient]::new()
97+
$client.GetStringAsync(
98+
$Url,
99+
$PSCmdlet.PipelineStopToken).GetAwaiter().GetResult()
100+
}
101+
102+
Invoke-WebGetRequest -Url https://httpbin.org/delay/10
103+
# Press ctrl+c to cancel
104+
```
105+
72106
## See also
73107

74108
- [about_Functions][05]
@@ -85,3 +119,4 @@ Advanced functions differ from compiled cmdlets in the following ways:
85119
[04]: about_Functions_OutputTypeAttribute.md
86120
[05]: about_Functions.md
87121
[06]: about_Variables.md
122+
[07]: xref:System.Threading.CancellationToken

0 commit comments

Comments
 (0)