Setting Windows PowerShell environment variables

前端 未结 18 1918
日久生厌
日久生厌 2020-11-22 11:03

I have found out that setting the PATH environment variable affects only the old command prompt. PowerShell seems to have different environment settings. How do I change the

18条回答
  •  情深已故
    2020-11-22 11:21

    All the answers suggesting a permanent change have the same problem: They break the path registry value.

    SetEnvironmentVariable turns the REG_EXPAND_SZ value %SystemRoot%\system32 into a REG_SZ value of C:\Windows\system32.

    Any other variables in the path are lost as well. Adding new ones using %myNewPath% won't work any more.

    Here's a script Set-PathVariable.ps1 that I use to address this problem:

     [CmdletBinding(SupportsShouldProcess=$true)]
     param(
         [parameter(Mandatory=$true)]
         [string]$NewLocation)
    
     Begin
     {
    
     #requires –runasadministrator
    
         $regPath = "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
         $hklm = [Microsoft.Win32.Registry]::LocalMachine
    
         Function GetOldPath()
         {
             $regKey = $hklm.OpenSubKey($regPath, $FALSE)
             $envpath = $regKey.GetValue("Path", "", [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
             return $envPath
         }
     }
    
     Process
     {
         # Win32API error codes
         $ERROR_SUCCESS = 0
         $ERROR_DUP_NAME = 34
         $ERROR_INVALID_DATA = 13
    
         $NewLocation = $NewLocation.Trim();
    
         If ($NewLocation -eq "" -or $NewLocation -eq $null)
         {
             Exit $ERROR_INVALID_DATA
         }
    
         [string]$oldPath = GetOldPath
         Write-Verbose "Old Path: $oldPath"
    
         # Check whether the new location is already in the path
         $parts = $oldPath.split(";")
         If ($parts -contains $NewLocation)
         {
             Write-Warning "The new location is already in the path"
             Exit $ERROR_DUP_NAME
         }
    
         # Build the new path, make sure we don't have double semicolons
         $newPath = $oldPath + ";" + $NewLocation
         $newPath = $newPath -replace ";;",""
    
         if ($pscmdlet.ShouldProcess("%Path%", "Add $NewLocation")){
    
             # Add to the current session
             $env:path += ";$NewLocation"
    
             # Save into registry
             $regKey = $hklm.OpenSubKey($regPath, $True)
             $regKey.SetValue("Path", $newPath, [Microsoft.Win32.RegistryValueKind]::ExpandString)
             Write-Output "The operation completed successfully."
         }
    
         Exit $ERROR_SUCCESS
     }
    

    I explain the problem in more detail in a blog post.

提交回复
热议问题