When we do code in c#, we have using statement to dispose our objects. so we don’t have to. :). What about PowerShell? Can we do that?
Here is a PowerShell function which behaves as using statement. 🙂
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Function Using-Object( | |
| [System.IDisposable] | |
| $InputObject, | |
| [scriptblock] | |
| $ScriptBlock = {throw "ScriptBlock is mandatory, please provide a value."}) | |
| { | |
| try | |
| { | |
| . $ScriptBlock | |
| } | |
| finally | |
| { | |
| if ($null -ne $InputObject -and $InputObject -is [System.IDisposable]) | |
| { | |
| $InputObject.Dispose() | |
| } | |
| } | |
| } |
So whenever we are dealing with an object that should be disposed we can use this function as below.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # $Connection object will be diposed. | |
| Using-Object($Connection = New-Object System.Data.SQLClient.SQLConnection($ConnectionString)) { | |
| #code goes here. | |
| } |
Isn’t that cool? 🙂