M HYPE SPLASH
// general

Set PSModulePath Environment Variable with PowerShell in Windows 10

By Abigail Rogers

I don't understand this. So currently my system environment variable named "PSModulePath" looks like this:

%ProgramFiles%\WindowsPowerShell\Modules;%SystemRoot%\system32\WindowsPowerShell\v1.0\Modules

Now observe the following PowerShell script:

$envarname = "PSModulePath"
$envar = (get-item env:$envarname).Value
[Environment]::SetEnvironmentVariable($envarname, $envar + ";C:\Expedited", "Machine")

All it should be doing is adding the path "C:\Expedited" to the PSModulesPath environment variable, right? Well, after running this script as administrator, the PSModulePath environment variable changes into this:

C:\Users\Username\Documents\WindowsPowerShell\Modules;C:\Program Files\WindowsPowerShell\Modules;C:\Windows\system32\WindowsPowerShell\v1.0\Modules;C:\Expedited

Notice how:

  1. There were originally two paths, each of which contained percentage signs (variables) in the original, but afterward they all changed directly into hard-coded paths.
  2. The "C:\Users\Username\Documents\WindowsPowerShell\Modules" path sprung out of nowhere (it wasn't in the original!)

I don't have any idea why either of these two things happened. When adding a path to this variable, I would like to keep it as close to the original as possible, not make all these other changes. Is there any way to preserve the percentage signs that were lost? How do I edit this environment variable correctly from within PowerShell?

2

2 Answers

PowerShell - Get OS Environmental Variables without Expanding

You can use the Get-Item cmdlet with the -path parameter and then pass that the path of the registry key containing the PSModulePath environmental variable.

You can then use the RegistryKey.GetValue Method along with DoNotExpandEnvironmentNames to get the string value of the PSModulePath environmental variable without expanding it.


PowerShell

$envarname = "PSModulePath"
$regkey = Get-Item -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
$envar = $regkey.GetValue($envarname, "", "DoNotExpandEnvironmentNames")
ECHO $envar

Note: You will want to be sure you run this from administrator elevated PowerShell command prompt or ISE screen for it to work correctly.

enter image description here


Further Resources

1

You are doing extra steps that are not really needed for your end goal. Just use the default as shown in the MS guidance.

So, based on the above article, you should only need that last example, or just one line, by using the built-in default / automatic environment variables.

[System.Environment]::SetEnvironmentVariable("PSModulePath", $Env:PSModulePath + ";C:\Expedited","Machine")
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy