forked from beatcracker/Powershell-Misc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Use-Object.ps1
60 lines (50 loc) · 1.92 KB
/
Use-Object.ps1
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
54
55
56
57
58
59
60
<#
.Synopsis
PowerShell-style version of C# 'using' statement.
This function will take care of disposing .NET and releasing COM objects for you.
.Description
PowerShell-style version of C# 'using' statement.
I felt that C# syntax is no quite fit for PowerShell, so I've made a 'pipelined' version.
The object is passed via the pipeline and scriptblock is passed as parameter.
The object is available to the scriptblock via $_ variable, similarly to 'ForEach-Obect'.
More details here: https://beatcracker.wordpress.com/2017/12/09/yet-another-using-statement/
.Parameter ScriptBlock
Scriptblock to execute, use '$_' to access object.
.Example
New-Object -TypeName System.IO.StreamWriter -ArgumentList 'c:\foo.txt' | Use-Object {$_.WriteLine('BAR')}
Use StreamWriter to write text to file. Stream will be disposed and closed after scriptblock is executed.
.Example
New-Object -ComObject InternetExplorer.Application | Use-Object {
$_.Visible = $true
$_.navigate('https://bing.com')
Start-Sleep -Seconds 10
$_.Quit()
}
Use Internet Explorer to show website and release IE COM object afterwards.
#>
filter Use-Object {
Param (
[ValidateNotNullOrEmpty()]
[scriptblock]$ScriptBlock
)
try {
. $ScriptBlock
}
finally {
if ($_ -is [System.IDisposable]) {
'Disposing: {0}' -f $_.GetType().Name | Write-Verbose
if ($null -eq $DisposableObject.psbase) {
$_.Dispose()
}
else {
$_.psbase.Dispose()
}
}
elseif ($_ -is [System.__ComObject]) {
Write-Verbose 'Releasing COM object'
if ([System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($_)) {
Write-Error 'Failed to release COM object!'
}
}
}
}