From 51c33269cb9ea07bba1625168c28b4e7a0f3fdf0 Mon Sep 17 00:00:00 2001 From: bus1hero Date: Sat, 30 Jul 2022 15:21:40 +0300 Subject: [PATCH] feat: Update Mock-EnvironmentVariable Improve the performance of setting user environment variables by replacing the [Environment]::SetEnvironmentVariable method with setting the underlying registry directly. --- foo | 0 .../Public/Mock-EnvironmentVariable.ps1 | 28 +++++++++++++++++-- 2 files changed, 26 insertions(+), 2 deletions(-) delete mode 100644 foo diff --git a/foo b/foo deleted file mode 100644 index e69de29..0000000 diff --git a/src/PesterExtensions/Public/Mock-EnvironmentVariable.ps1 b/src/PesterExtensions/Public/Mock-EnvironmentVariable.ps1 index 5bfb149..20f92c4 100644 --- a/src/PesterExtensions/Public/Mock-EnvironmentVariable.ps1 +++ b/src/PesterExtensions/Public/Mock-EnvironmentVariable.ps1 @@ -1,3 +1,27 @@ +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] @@ -5,7 +29,7 @@ function Restore { ) 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 } } } @@ -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)