Functions/EnvManagement.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
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
235
236
237
238
239
240
# ===========================================================================
# EnvManagement.ps1 -------------------------------------------------------
# ===========================================================================

# function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
function Get-EnvVariable
{
    <#
    .DESCRIPTION
        Get detailed information about a environment variable of specific scope, or all existing environment variables.
 
    .PARAMETER Name
 
    .PARAMETER Scope
 
    .EXAMPLE
        PS C:\> Get-EnvVariable
 
        Name Value
        ---- -----
        ALLUSERSPROFILE C:\ProgramData
        ANDROID_SDK_HOME C:\Android
 
        -----------
        Description
        Return detailed information about all existing environment variables in scope process. All available environment variables can be accessed by autocompletion.
 
    .EXAMPLE
        PS C:\> Get-EnvVariable -Name 'ALLUSERSPROFILE' -Scope 'process'
 
        Name Scope
        ---- -----
        C:\ProgramData process
 
        -----------
        Description
        Return detailed information about environment variable 'ALLUSERSPROFILE' in scope process.
 
    .INPUTS
        Name
 
    .OUTPUTS
        System.Object. Information about specified environment variable
    #>


    [CmdletBinding(PositionalBinding)]
    
    [OutputType([System.Object])]

    Param(
        [Parameter(Position=1, ValueFromPipeline, ValueFromPipelineByPropertyName, HelpMessage="Name of environment variable")]
        [ValidateSet([ValidateSystemEnv])]
        [System.String] $Name,

        [Parameter(Position=2, HelpMessage="Scope of specified environment variable")]
        [ValidateSet("process", "machine", "user")]
        [System.String] $Scope = "process"
    )
  
    Process {

        $result = @()

        if ($Name) {
            # if name is specified return the environment variable, and split the elements if its elements are structured as list
            [System.Environment]::GetEnvironmentVariable($Name, $Scope) -Split ';' | ForEach-Object {
                if (-not [System.String]::IsNullOrWhiteSpace($_)) {
                    $result += [PSCustomObject] @{
                        Name   = $_
                        Scope  = $Scope
                    }
                }
            }
        } else {
            # return all environment variales in scope process
            $result = Get-ChildItem -Path "Env:"
        }

        return $result
    }
}

# function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
function Set-EnvVariable
{
    <#
    .DESCRIPTION
        Set environment variable with specific value.
 
    .PARAMETER Name
 
    .PARAMETER Value
 
    .PARAMETER Scope
 
    .EXAMPLE
        PS C:\> Set-EnvVariable -Name 'ALLUSERSPROFILE' -Value 'C:\ProgramData' -Scope 'process'
 
        -----------
        Description
        Set Environment variable 'ALLUSERSPROFILE' with value 'C:\ProgramData' in scope 'process'.
 
    .OUTPUTS
        None.
    #>


    [CmdletBinding(PositionalBinding)]
    
    [OutputType([Void])]

    Param(
        [Parameter(Position=1, Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName , HelpMessage="Name of environment variable")]
        [System.String] $Name,

        [Parameter(Position=2, Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName , HelpMessage="Value ofor specified environment variable")]
        [System.String] $Value,

        [Parameter(Position=3, HelpMessage="Scope of specified environment variable")]
        [ValidateSet("process", "machine", "user")]
        [System.String] $Scope = "process"
    )
  
    Process {

        [System.Environment]::SetEnvironmentVariable($Name, $Value, $Scope)

    }
}

# function ----------------------------------------------------------------
# ---------------------------------------------------------------------------
function Test-EnvPath {    
    <#
    .DESCRIPTION
        Test whether a path exists in environment of specific scope.
 
    .PARAMETER Path
 
    .PARAMETER Scope
 
    .EXAMPLE
        PS C:\> Test-EnvPath -Path 'C:\Windows' -SCope 'process'
        True
 
        -----------
        Description
        Return true if environment path contains path 'C:\Windows' in scope 'process'.
    .OUTPUTS
        Boolean. True if environment path contains specified parameter path.
    #>


    [CmdletBinding(PositionalBinding)]

    [OutputType([Boolean])]

    Param (    
        [Parameter(Position=1, ValueFromPipeline, HelpMessage="Path which will be searched for in environment path")]
        [System.String] $Path,

        [Parameter(Position=2, HelpMessage="Scope of specified environment variable")]
        [ValidateSet("process", "machine", "user")]
        [System.String] $Scope = "process"
    )

    Process {
        return $(if (Get-EnvVariable -Name "Path" -Scope $Scope | Where-Object -FilterScript { $_.Name -match $($Path -replace "\\", "\\")}) {$True} else {$False})
    }
}

# # function -------------------------------------------------------------------
# # ------------------------------------------------------------------------------
# function Repair-EnvironmentPath
# {
# <#
# .SYNOPSIS

# .DESCRIPTION

# .PARAMETER Name

# .PARAMETER Scope

# .EXAMPLE

# .NOTES
# #>

# [CmdletBinding(PositionalBinding=$True, SupportsShouldProcess=$True, ConfirmImpact="None")]

# [OutputType([Void])]
    
# Param (
# [Parameter()]
# [ValidateSet("process", "machine", "user")]
# [System.String] $Scope = "process"
# )

# Process {

# if ($Scope -eq 'process')
# {
# Write-Warning -Message 'This will change current-process value only. This may not be what you intended; see -Scope'
# }

# # Ensure unique paths only
# $paths = Get-EnvironmentVariable -Name "Path" -Scope $Scope
# $result = @()
# foreach ($path in ($paths | Select-Object -ExpandProperty Path))
# {
# if ([string]::IsNullOrWhiteSpace($path)) {
# Write-Verbose -Message 'Found empty path. Removing.'
# continue
# }

# $path = $path.Trim()
# if ($path -in $result) {
# Write-Warning -Message "Found duplicate path [$path]. Removing."
# if ($PSCmdlet.ShouldProcess($path, 'Removing duplicate path entry?')) {
# continue
# }
# }

# if (-not (Test-Path $path -PathType Container)) {
# Write-Warning -Message "Found invalid path [$path]. Removing."
# if ($PSCmdlet.ShouldProcess($path, 'Removing invalid path entry?')) {
# continue
# }
# }

# $result += $path
# }

# if ($PSCmdlet.ShouldProcess("`n$($result -join "`n")`n", 'Update environment with paths')){
# [Environment]::SetEnvironmentVariable("Path", $result -join ';', $Scope)
# }
# }
# }