Skip to content

Commit 51c3326

Browse files
committed
feat: Update Mock-EnvironmentVariable
Improve the performance of setting user environment variables by replacing the [Environment]::SetEnvironmentVariable method with setting the underlying registry directly.
1 parent 8456537 commit 51c3326

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

foo

Whitespace-only changes.

src/PesterExtensions/Public/Mock-EnvironmentVariable.ps1

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,35 @@
1+
function Set-EnvironmentVariable {
2+
param (
3+
[string]
4+
$Variable,
5+
6+
[string]
7+
$Value,
8+
9+
[EnvironmentVariableTarget]
10+
$Target
11+
)
12+
if ($Target -eq [System.EnvironmentVariableTarget]::Process) {
13+
[System.Environment]::SetEnvironmentVariable($Variable, $value, 'Process')
14+
}
15+
elseif ($Target -eq [System.EnvironmentVariableTarget]::User) {
16+
if ($Value) {
17+
New-ItemProperty -Path 'HKCU:\Environment' -Name $Variable -Value $Value -Force > $null
18+
}
19+
else {
20+
Remove-ItemProperty -Path 'HKCU:\Environment' -Name $Variable -ErrorAction Ignore
21+
}
22+
}
23+
}
24+
125
function Restore {
226
param (
327
[hashtable]
428
$Backup
529
)
630
foreach ($variable in $Backup.Keys) {
731
foreach ($target in $Backup.$variable.Keys) {
8-
[Environment]::SetEnvironmentVariable($variable, $Backup.$variable.$target, $target)
32+
Set-EnvironmentVariable -Variable $variable -Value $Backup.$variable.$target -Target $target
933
}
1034
}
1135
}
@@ -29,7 +53,7 @@ function Backup {
2953
$OriginalValue = [Environment]::GetEnvironmentVariable($variable, $target)
3054
$VariableBackup.Add($target, $OriginalValue)
3155
if ($Value) {
32-
[Environment]::SetEnvironmentVariable($variable, $Value, $target)
56+
Set-EnvironmentVariable -Variable $variable -Value $value -Target $target
3357
}
3458
}
3559
$Backup.Add($variable, $VariableBackup)

0 commit comments

Comments
 (0)