首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >powershell脚本中的引用默认路径

powershell脚本中的引用默认路径
EN

Stack Overflow用户
提问于 2022-04-30 19:42:58
回答 2查看 110关注 0票数 2

如果路径已在当前终端中更改,是否有方法调用系统路径?即:

代码语言:javascript
运行
复制
$env:Path = "C:\some new path"   
#some coding that requires a different path set up
$env:Path = $defaultPath #would have to define $defaultPath by calling the system default path
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-04-30 22:22:10

使用以下方法从注册表重新加载$env:PATH环境变量,因为以后的会话将看到它(假设没有进行进一步的相关注册表更新)。

如果当前会话没有进行任何相关的注册表更新,这与获取会话启动时生效的值相同--禁止通过$PROFILE script进行任何动态添加。

代码语言:javascript
运行
复制
$env:PATH = [Environment]::GetEnvironmentVariable('Path', 'Machine'),
            [Environment]::GetEnvironmentVariable('Path', 'User') -join ';'

注意:

  • 进程的有效$env:PATH值是机器级和用户级注册表项的复合值,机器级定义优先,如上面的两个.NET API调用所反映的那样。

代码语言:javascript
运行
复制
- Note that the underlying registry locations - `HKEY_LOCAL_MACHIN\System\CurrentControlSet\Control\Session Manager\Environment` and `HKEY_CURRENT_USER\Environment` - are `REG_EXPAND_SZ` registry values, i.e. they may be defined in terms of _other_ environment variables, such as `%SystemRoot%` and `%ProgramFiles%`.
代码语言:javascript
运行
复制
- Both the .NET API calls above - using [`[Environment]::GetEnvironmentVariable()`](https://learn.microsoft.com/en-US/dotnet/api/System.Environment.GetEnvironmentVariable) - and PowerShell's [`Get-ItemProperty`](https://learn.microsoft.com/powershell/module/microsoft.powershell.management/get-itemproperty) and [`Get-ItemPropertyValue`](https://learn.microsoft.com/powershell/module/microsoft.powershell.management/get-itempropertyvalue) cmdlets _expand_ (interpolate) such references and return _verbatim_ paths - which is what new processes see by default too.

鉴于上述情况,唯一可靠地检索会话启动时有效值的方法是在启动时将其保存在变量中。

票数 3
EN

Stack Overflow用户

发布于 2022-04-30 20:10:48

它仍然存储在注册表中,所以您只需查询它:

定位:HKLM:\System\CurrentControlSet\Control\Session Manager\Environment

代码语言:javascript
运行
复制
$key = "HKCU:\Environment",
       "HKLM:\System\CurrentControlSet\Control\Session Manager\Environment"
       
(Get-ItemPropertyValue -Path $key -Name Path) -Join ';'

使用Get-ItemPropertyValue查询密钥(如建议的那样)只会给出属性的值。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72071650

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档