如何在不扩展令牌的情况下获取PATH环境变量的值? [英] How to get the value of the PATH environment variable without expanding tokens?

查看:101
本文介绍了如何在不扩展令牌的情况下获取PATH环境变量的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个PowerShell脚本,以将PATH环境变量中的文件夹名称转换为短名称并保存更改.它适用于显式路径,但可以扩展标记,因此当我保存更改时,标记将替换为显式路径.我想保留令牌.

I'm writing a PowerShell script to convert folder names to short names in the PATH environment variable and save the changes. It works correctly for explicit paths, but it expands tokens, so when I save my changes the tokens are replaced with explicit paths. I'd like to preserve the tokens.

例如,如果我的PATH是这样的:%SystemRoot%;%SystemRoot%\system32;C:\Program Files\TortoiseSVN\bin;C:\ProgramData\chocolatey\bin

For example, if my PATH is this: %SystemRoot%;%SystemRoot%\system32;C:\Program Files\TortoiseSVN\bin;C:\ProgramData\chocolatey\bin

我想要这个结果:%SystemRoot%;%SystemRoot%\system32;C:\PROGRA~1\TORTOI~1\bin;C:\PROGRA~3\CHOCOL~1\bin

但是我却得到了:C:\Windows;C:\Windows\system32;C:\PROGRA~1\TORTOI~1\bin;C:\PROGRA~3\CHOCOL~1\bin

这是说明问题的完整脚本.

Here's the full script that illustrates the problem.

# get the current path.
# I ended up not using either of these approaches because they appear to
# be contextual; on my system, at least, they include paths that aren't
# seen when I view the PATH value from the System Properties -> Environment
# Variables dialog box.
$current_path = $env:Path
$current_path = [System.Environment]::GetEnvironmentVariable("Path")

# Instead, I get the PATH value directly from the registry, like so:
$current_path = (Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' -Name Path).Path

# The problem is that PowerShell expands the tokens even when reading from the 
# registry, so I can't detect the tokens and ignore them.  What I really want
# is just the literal string value, with no token evaluation.
# Here's a sample value; this is what I see in regedt32 and the system dialogs,
# but it's not what I get from the line above.
$current_path = '%SystemRoot%;%SystemRoot%\system32;C:\Program Files\TortoiseSVN\bin;C:\ProgramData\chocolatey\bin'

$new_path = ''

# the FileSystemObject has a method to convert the path using short names for the folders.
$fso = New-Object -ComObject Scripting.FileSystemObject

# Individual paths are delimited by a semicolon.  Skip paths with tokens, 
# and preserve trailing slashes in each path.
$current_path.Split(';') |
    ForEach-Object { 
        if ($_.StartsWith('%'))
            { $_ }
        elseif ($_.EndsWith('\'))
            { "$($fso.GetFolder($_).ShortPath)\" }
        else
            { "$($fso.GetFolder($_).ShortPath)" } 
    } |
    ForEach-Object { $new_path += "$_;" }

# remove the extra semicolon from the end the new PATH.
$new_path = $new_path.TrimEnd(";")

"Current PATH length: $($current_path.Length)"
"New PATH length: $($new_path.Length)"

$new_path

# commented out so you don't accidentally update your path if you try out this script
#[System.Environment]::SetEnvironmentVariable("Path", $new_path, "Machine")

如果我可以从注册表中获取文字字符串值,这似乎应该很容易,但是到目前为止,我还无法弄清楚该怎么做.

It seems like it should be easy enough if I could just get the literal string value from the registry, but I so far have not been able to figure out how to do that.

推荐答案

这本身不是PowerShell,而是基础Windows注册表的功能". Path变量的类型为REG_EXPAND_SZ,可在检索时自动扩展环境变量.我认为您无法使用内置cmdlet解决它,但是可以使用.NET Microsoft.Win32.Registry API.将RegistryKey.GetValue重载与RegistryValueOptions.DoNotExpandEnvironmentNames一起使用:

This isn't PowerShell per se, but a "feature" of the underlying Windows registry. The Path variable is of type REG_EXPAND_SZ which automatically expands environment variables on retrieval. I don't think you can get around it with the built-in cmdlets, but you can with the .NET Microsoft.Win32.Registry APIs. Use the RegistryKey.GetValue overload with RegistryValueOptions.DoNotExpandEnvironmentNames:

$regKey = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey('SYSTEM\CurrentControlSet\Control\Session Manager\Environment', $true)
$regKey.GetValue('Path', $null, "DoNotExpandEnvironmentNames")

当需要保存变量时,请使用SetValueRegistryValueKind.ExpandString的重载将其保存为正确的类型:

when it is time to save the variable, use the overload of SetValue with RegistryValueKind.ExpandString to save it with the correct type:

$regKey.SetValue("Path", $new_path, "ExpandString")

这篇关于如何在不扩展令牌的情况下获取PATH环境变量的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆