Skip to content
santisqPublic

About

C# using statement for PowerShell

Topics

Resources

Stars

3 stars

Watchers

1 watching

Forks

Repository files navigation

PSUsing

C# using statement for PowerShell


build codecov PowerShell Gallery LICENSE

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().

Documentation

Check out the docs for information about how to use this Module.

Installation

Gallery

The module is available through the PowerShell Gallery:

Install-Module PSUsing -Scope CurrentUser

Source

git clone 'https://github.com/santisq/PSUsing.git'
Set-Location ./PSUsing
./build.ps1

Requirements

Compatible with Windows PowerShell v5.1 and PowerShell 7+.

Usage

The most common pattern would be

use ($myobj = [DisposableObject]::new()) {
   # do stuff with:
   $myObj
}

The cmdlet can also process pipeline input, for example

0..10 | use ($myobj = [DisposableObject]::new()) {
   $myObj.DoStuff($_)
}

And can span different processing methods

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

The token can be cancelled on a timeout too

# would throw a `TaskCanceledException` after 5 seconds
use -ct 5 -sb {
   param($token)

   [System.Threading.Tasks.Task]::Delay(-1, $token).GetAwaiter().GetResult()
}

Contributing

Contributions are welcome, if you wish to contribute, fork this repository and submit a pull request with the changes.

About

C# using statement for PowerShell

Topics

Resources

Stars

3 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages