[英]How do I handle Windows PATH variable expansion when set from PowerShell?
I am tweaking the PATH on several W2k3 servers in PowerShell to convert certain paths with blank spaces to their 8.3 equivalents. 我在PowerShell中的几个W2k3服务器上调整PATH,将带有空格的某些路径转换为8.3当量。 After several regex transformations, I run the following two commands:
经过几次正则表达式转换后,我运行以下两个命令:
# Set the path for this process
$env:PATH = $path
# Set the path for the Machine
[System.Environment]::SetEnvironmentVariable('PATH', $path,[System.EnvironmentVariableTarget]::Machine)
After running them, the path is changed in ways I didn't intend. 运行它们之后,路径会以我不想要的方式改变。 %SystemRoot% is uniformly expanded to C:\\Windows.
%SystemRoot%统一扩展为C:\\ Windows。 I can't see where this signals the apocalypse, but I'd rather keep the %SystemRoot%, so I fiddled until I got %SystemRoot% to appear in the path again, but when I do the path no longer expands and no longer works.
我无法看到这表示天启的意义,但我宁愿保留%SystemRoot%,所以我摆弄,直到我让%SystemRoot%再次出现在路径中,但是当我做的路径不再扩展而不再作品。 Echoing the path at the CLI returns an unexpanded string (this is wrong) and commands in the SystemRoot can no longer be found.
在CLI处回显路径会返回未展开的字符串(这是错误的),并且无法再找到SystemRoot中的命令。
If I then add a null entry to the Path ";;", without altering any other text in the PATH, it begins to work correctly. 如果我然后在路径“;;”中添加一个空条目,而不改变PATH中的任何其他文本,它开始正常工作。
So my question is how to alter the path programmatically using PowerShell so as not to muck up variable expansion within the path? 所以我的问题是如何使用PowerShell以编程方式改变路径,以免破坏路径中的变量扩展?
As far as I can tell, you can't do this with the [Environment]::SetEnvironmentVariable()
method and you can't do this with the Registry provider. 据我所知,您无法使用
[Environment]::SetEnvironmentVariable()
方法执行此操作,并且您无法使用Registry提供程序执行此操作。 However you can access the system Path env var in the registry using the Microsoft.Win32.RegistryKey
class like so: 但是,您可以使用
Microsoft.Win32.RegistryKey
类访问注册表中的系统Path env var,如下所示:
C:\PS> $key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey('SYSTEM\CurrentControlSet\Control\Session Manager\Environment', $true) C:\PS> $path = $key.GetValue('Path',$null,'DoNotExpandEnvironmentNames') C:\PS> $path ...;%systemroot%\System32\WindowsPowerShell\v1.0\ C:\PS> $key.SetValue('Path', $path + ';%Windir%\Symbols', 'ExpandString') C:\PS> $key.Dispose()
This will allow you to save the updated PATH and preserve the variables that appear in the Path value. 这将允许您保存更新的PATH并保留Path值中显示的变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.