Saritasa.General.psm1

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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
<#
.Synopsis
    Fetches "Preference" variable values from the caller's scope.
.DESCRIPTION
    Script module functions do not automatically inherit their caller's variables, but they can be
    obtained through the $PSCmdlet variable in Advanced Functions. This function is a helper function
    for any script module Advanced Function; by passing in the values of $ExecutionContext.SessionState
    and $PSCmdlet, Get-CallerPreference will set the caller's preference variables locally.
.PARAMETER Cmdlet
    The $PSCmdlet object from a script module Advanced Function.
.PARAMETER SessionState
    The $ExecutionContext.SessionState object from a script module Advanced Function. This is how the
    Get-CallerPreference function sets variables in its callers' scope, even if that caller is in a different
    script module.
.PARAMETER Name
    Optional array of parameter names to retrieve from the caller's scope. Default is to retrieve all
    Preference variables as defined in the about_Preference_Variables help file (as of PowerShell 4.0)
    This parameter may also specify names of variables that are not in the about_Preference_Variables
    help file, and the function will retrieve and set those as well.
.EXAMPLE
    Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
 
    Imports the default PowerShell preference variables from the caller into the local scope.
.EXAMPLE
    Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState -Name 'ErrorActionPreference','SomeOtherVariable'
 
    Imports only the ErrorActionPreference and SomeOtherVariable variables into the local scope.
.EXAMPLE
    'ErrorActionPreference','SomeOtherVariable' | Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
 
    Same as Example 2, but sends variable names to the Name parameter via pipeline input.
.INPUTS
    String
.OUTPUTS
    None. This function does not produce pipeline output.
.LINK
    about_Preference_Variables
.NOTES
    Import Preference variables from the caller of a Script Module function
    https://gallery.technet.microsoft.com/scriptcenter/Inherit-Preference-82343b9d
    MICROSOFT LIMITED PUBLIC LICENSE
#>

function Get-CallerPreference
{
    [CmdletBinding(DefaultParameterSetName = 'AllVariables')]
    param (
        [Parameter(Mandatory = $true)]
        [ValidateScript({ $_.GetType().FullName -eq 'System.Management.Automation.PSScriptCmdlet' })]
        $Cmdlet,

        [Parameter(Mandatory = $true)]
        [System.Management.Automation.SessionState]
        $SessionState,

        [Parameter(ParameterSetName = 'Filtered', ValueFromPipeline = $true)]
        [string[]]
        $Name
    )

    begin
    {
        $filterHash = @{}
    }

    process
    {
        if ($null -ne $Name)
        {
            foreach ($string in $Name)
            {
                $filterHash[$string] = $true
            }
        }
    }

    end
    {
        # List of preference variables taken from the about_Preference_Variables help file in PowerShell version 4.0

        $vars = @{
            'ErrorView' = $null
            'FormatEnumerationLimit' = $null
            'LogCommandHealthEvent' = $null
            'LogCommandLifecycleEvent' = $null
            'LogEngineHealthEvent' = $null
            'LogEngineLifecycleEvent' = $null
            'LogProviderHealthEvent' = $null
            'LogProviderLifecycleEvent' = $null
            'MaximumAliasCount' = $null
            'MaximumDriveCount' = $null
            'MaximumErrorCount' = $null
            'MaximumFunctionCount' = $null
            'MaximumHistoryCount' = $null
            'MaximumVariableCount' = $null
            'OFS' = $null
            'OutputEncoding' = $null
            'ProgressPreference' = $null
            'PSDefaultParameterValues' = $null
            'PSEmailServer' = $null
            'PSModuleAutoLoadingPreference' = $null
            'PSSessionApplicationName' = $null
            'PSSessionConfigurationName' = $null
            'PSSessionOption' = $null

            'ErrorActionPreference' = 'ErrorAction'
            'DebugPreference' = 'Debug'
            'ConfirmPreference' = 'Confirm'
            'WhatIfPreference' = 'WhatIf'
            'VerbosePreference' = 'Verbose'
            'WarningPreference' = 'WarningAction'
            'InformationPreference' = 'InformationAction'
        }


        foreach ($entry in $vars.GetEnumerator())
        {
            if (([string]::IsNullOrEmpty($entry.Value) -or -not $Cmdlet.MyInvocation.BoundParameters.ContainsKey($entry.Value)) -and
                ($PSCmdlet.ParameterSetName -eq 'AllVariables' -or $filterHash.ContainsKey($entry.Name)))
            {
                $variable = $Cmdlet.SessionState.PSVariable.Get($entry.Key)

                if ($null -ne $variable)
                {
                    if ($SessionState -eq $ExecutionContext.SessionState)
                    {
                        Set-Variable -Scope 1 -Name $variable.Name -Value $variable.Value -Force -Confirm:$false -WhatIf:$false
                    }
                    else
                    {
                        $SessionState.PSVariable.Set($variable.Name, $variable.Value)
                    }
                }
            }
        }

        if ($PSCmdlet.ParameterSetName -eq 'Filtered')
        {
            foreach ($varName in $filterHash.Keys)
            {
                if (-not $vars.ContainsKey($varName))
                {
                    $variable = $Cmdlet.SessionState.PSVariable.Get($varName)

                    if ($null -ne $variable)
                    {
                        if ($SessionState -eq $ExecutionContext.SessionState)
                        {
                            Set-Variable -Scope 1 -Name $variable.Name -Value $variable.Value -Force -Confirm:$false -WhatIf:$false
                        }
                        else
                        {
                            $SessionState.PSVariable.Set($variable.Name, $variable.Value)
                        }
                    }
                }
            }
        }

    } # end

} # function Get-CallerPreference

<#
.SYNOPSIS
Returns $true if hostname represents local PC.
#>

function Test-IsLocalhost
{
    [CmdletBinding()]
    param
    (
        [string] $ComputerName
    )

    $ComputerName -match "^(\.|localhost|$env:COMPUTERNAME)`$"
}

<#
.SYNOPSIS
Dispose an object after using it.
 
.DESCRIPTION
This cmdlet is designed to use the same way the "using" keyword in C# is used.
 
.PARAMETER InputObject
Object to be disposed.
 
.PARAMETER ScriptBlock
Script to be executed.
 
.EXAMPLE
C:\PS> $text = ""
C:\PS> $fileStream = New-Object System.IO.FileStream("G:\test\1.txt", [System.IO.FileMode]::Open)
C:\PS> Use-Object $fileStream `
{
    $streamReader = New-Object System.IO.StreamReader($fileStream)
    Use-Object $streamReader `
    {
        $text = $streamReader.ReadToEnd()
    }
}
C:\PS> $text
#>

function Use-Object
{
    [CmdletBinding()]
    param
    (
        # Object to be disposed.
        [Parameter(Mandatory = $true)]
        [AllowEmptyString()]
        [AllowEmptyCollection()]
        [AllowNull()]
        [Object]
        $InputObject,

        # Code to be executed after which the object will be disposed
        [Parameter(Mandatory = $true)]
        [scriptblock]
        $ScriptBlock
    )

    try
    {
        . $ScriptBlock
    }
    finally
    {
        if ($null -ne $InputObject -and $InputObject -is [System.IDisposable])
        {
            $InputObject.Dispose()
        }
    }
}