PSUsing is a little PowerShell Module that provides an easy way to invoke a script block that can span different Input processing methods and automatically clean-up resources when completed.
Resource cleanup is enforced for the same scenarios as the ones detailed in clean
block:
- When the pipeline execution finishes normally without terminating error.
- When the pipeline execution is interrupted due to terminating error.
- When the pipeline is halted by
Select-Object -First
. - When the pipeline is being stopped by CTRL + C or
StopProcessing()
.
Check out the docs for information about how to use this Module.
The module is available through the PowerShell Gallery:
Install-Module PSUsing -Scope CurrentUser
git clone 'https://github.com/santisq/PSUsing.git'
Set-Location ./PSUsing
./build.ps1
Compatible with Windows PowerShell v5.1 and PowerShell 7+.
use ($myobj = [DisposableObject]::new()) {
# do stuff with:
$myObj
}
0..10 | use ($myobj = [DisposableObject]::new()) {
$myObj.DoStuff($_)
}
0..10 | use ($myobj = [DisposableObject]::new()) {
begin { 'begin' }
process { $myObj.DoStuff($_) }
end { 'end' }
}
A CancellationToken
is available for .NET methods that support it
Note
The cancellation source is tied to the cmdlet's StopProcessing()
method.
# can CTRL+C out of this
use -sb {
param($token)
[System.Threading.Tasks.Task]::Delay(-1, $token).Wait()
}
# can stop this
$job = Start-Job {
use -sb {
param($token)
[System.Threading.Tasks.Task]::Delay(-1, $token).Wait()
}
}
Start-Sleep 1
$job | Stop-Job
# would throw a `TaskCanceledException` after 5 seconds
use -ct 5 -sb {
param($token)
[System.Threading.Tasks.Task]::Delay(-1, $token).GetAwaiter().GetResult()
}
Contributions are welcome, if you wish to contribute, fork this repository and submit a pull request with the changes.