- Begin by creating a class in C#. You can also save the code in a separate file such as Code.cs. See help Add-Type -Examples for additional examples. The class must also inherit from System.IDisposable, otherwise the using-block function will complain with something like 'using-block : Cannot process argument transformation on parameter 'InputObject'. Cannot convert the "Code" value of type "Code" to type "System.IDisposable".'
- Create your using block with the instantiation of a new object in parentheses.
- Finally, in the script block place your needed logic.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | Add -Type @" using System; public class Code : IDisposable { public Code() { Name = "Michael" ; } public string Name { get; set ; } public bool IsDisposed { get; set ; } public void Dispose() { Dispose(true); GC .SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!IsDisposed) { IsDisposed = true; } } } "@ function using -block { param ( [System.IDisposable] $InputObject = $(throw "The parameter -inputObject is required." ), [ScriptBlock] $ScriptBlock = $(throw "The parameter -scriptBlock is required." ) ) try { & $ScriptBlock } finally { if ( $InputObject ) { if ( $InputObject .PSBase) { $InputObject .PSBase.Dispose() } else { $InputObject .Dispose() } } } } using -block ( $c = New-Object Code) { $name = $c .Name $name # Michael $c .IsDisposed # False } $name # Not in this scope so no value $c .IsDisposed # True |