Skip to content

Commit

Permalink
feat: Update Mock-EnvironmentVariable
Browse files Browse the repository at this point in the history
Improve the performance of setting user environment variables by
replacing the [Environment]::SetEnvironmentVariable method with setting
the underlying registry directly.
  • Loading branch information
BusHero committed Jul 30, 2022
1 parent 8456537 commit 51c3326
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
Empty file removed foo
Empty file.
28 changes: 26 additions & 2 deletions src/PesterExtensions/Public/Mock-EnvironmentVariable.ps1
Original file line number Diff line number Diff line change
@@ -1,11 +1,35 @@
function Set-EnvironmentVariable {
param (
[string]
$Variable,

[string]
$Value,

[EnvironmentVariableTarget]
$Target
)
if ($Target -eq [System.EnvironmentVariableTarget]::Process) {
[System.Environment]::SetEnvironmentVariable($Variable, $value, 'Process')
}
elseif ($Target -eq [System.EnvironmentVariableTarget]::User) {
if ($Value) {
New-ItemProperty -Path 'HKCU:\Environment' -Name $Variable -Value $Value -Force > $null
}
else {
Remove-ItemProperty -Path 'HKCU:\Environment' -Name $Variable -ErrorAction Ignore
}
}
}

function Restore {
param (
[hashtable]
$Backup
)
foreach ($variable in $Backup.Keys) {
foreach ($target in $Backup.$variable.Keys) {
[Environment]::SetEnvironmentVariable($variable, $Backup.$variable.$target, $target)
Set-EnvironmentVariable -Variable $variable -Value $Backup.$variable.$target -Target $target
}
}
}
Expand All @@ -29,7 +53,7 @@ function Backup {
$OriginalValue = [Environment]::GetEnvironmentVariable($variable, $target)
$VariableBackup.Add($target, $OriginalValue)
if ($Value) {
[Environment]::SetEnvironmentVariable($variable, $Value, $target)
Set-EnvironmentVariable -Variable $variable -Value $value -Target $target
}
}
$Backup.Add($variable, $VariableBackup)
Expand Down

0 comments on commit 51c3326

Please sign in to comment.