如果 PowerShell 中的环境变量不存在,如何设置它?

2024-01-01

我很惊讶在谷歌搜索一段时间后我没有得到这种常见情况的答案......

如果环境变量不存在,如何在 PowerShell 中设置它?


下面的代码定义了环境变量FOO对于当前进程(如果尚不存在)。

if ($null -eq $env:FOO) { $env:FOO = 'bar' }

# If you want to treat a *nonexistent* variable the same as
# an existent one whose value is the *empty string*, you can simplify to:
if (-not $env:FOO) { $env:FOO = 'bar' }

# Alternatively:
if (-not (Test-Path env:FOO)) { $env:FOO = 'bar' }

# Or even (quietly fails if the variable already exists):
New-Item -ErrorAction Ignore env:FOO -Value bar

In PowerShell(核心)7.1+, 其中有空合并运算符 https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Operators#null-coalescing-assignment-operator-,您可以简化为:

$env:FOO ??= 'bar'

Note:
Environment variables are strings by definition. If a given environment variable is defined, but has no value, its value is the empty string ('') rather than $null. Thus, comparing to $null can be used to distinguish between an undefined environment variable and one that is defined, but has no value. However, note that assigning to environment variables in PowerShell / .NET makes no distinction between $null and '', and either value results in undefining (removing) the target environment variable; similarly, in cmd.exe set FOO= results in removal/non-definition of variable FOO, and the GUI dialog (accessible via sysdm.cpl) doesn't allow you to define a variable with an empty string either. However, the Windows API (SetEnvironmentVariable https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-setenvironmentvariable) does permit creating environment variables that contain the empty string.
On Unix-like platforms, empty-string values are allowed too, and the native, POSIX-compatible shells (e.g, bash and /bin/sh) - unlike PowerShell - also allow you to create them (e.g, export FOO=). Note that environment variable definitions and lookups are case-sensitive on Unix, unlike on Windows.

Note: If the environment variable is created on demand by the assignment above ($env:FOO = ...), it will exist for the current process and any child processes it creates only Thanks, PetSerAl https://stackoverflow.com/users/4003407/petseral.


The following was mostly contributed by Ansgar Wiechers https://stackoverflow.com/users/1630171/ansgar-wiechers, with a supplement by Mathias R. Jessen https://stackoverflow.com/users/712649/mathias-r-jessen:

On Windows[*], if you want to define an environment variable persistently, you need to use the static SetEnvironmentVariable() https://learn.microsoft.com/en-US/dotnet/api/System.Environment.SetEnvironmentVariable method of the [System.Environment] https://learn.microsoft.com/en-US/dotnet/api/System.Environment class:

# user environment
[Environment]::SetEnvironmentVariable('FOO', 'bar', 'User')

# system environment (requires admin privileges)
[Environment]::SetEnvironmentVariable('FOO', 'bar', 'Machine')

请注意,这些定义生效于future会话(进程),所以按顺序定义变量current过程as well, run $env:FOO = 'bar' 此外,这实际上等同于[Environment]::SetEnvironmentVariable('FOO', 'bar', 'Process').

When using [Environment]::SetEnvironmentVariable() with User or Machine, a WM_SETTINGCHANGE https://msdn.microsoft.com/en-us/library/windows/desktop/ms725497%28v=vs.85%29.aspx message is sent to other applications to notify them of the change (though few applications react to such notifications).
This doesn't apply when targeting Process (or when assigning to $env:FOO), because no other applications (processes) can see the variable anyway.

也可以看看:创建和修改环境变量 https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-powershell-1.0/ff730964(v=technet.10)(TechNet 文章)。


[*] On Unix-like platforms, attempts to target the persistent scopes - User or Machine- are quietly ignored, as of .NET (Core) 7, and this non-support for defining persistent environment variables is unlikely to change, given the lack of a unified mechanism across Unix platforms.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如果 PowerShell 中的环境变量不存在,如何设置它? 的相关文章

随机推荐

  • NotificationCompat.Builder() 不接受 Channel Id 作为参数

    我知道这个问题之前已经被问过好几次了 但这些解决方案都不适合我 这就是为什么我想再次问这个问题 以下行仅接受NotificationCompat Builder context NotificationCompat Builder noti
  • 项目构建失败:任务“compileDebug”在根项目中不明确

    当我将我的项目与梯度文件一切顺利 我明白了建设成功gradle 控制台上有消息 但是当我运行我的项目时 我收到以下消息 FAILED FAILURE Build failed with an exception What went wron
  • 在 JS 中使用 Bootstrap 颜色

    我正在使用 Google Chart 并希望将切片颜色设置为 bootstrap 使用的颜色 例如badge success or badge danger 有什么方法可以从 JavaScript 中访问这些颜色代码吗 如果您使用 Boot
  • web3 websocket连接阻止节点进程退出

    我有一个创建 web3 websocket 连接的 Node js 进程 如下所示 web3 new Web3 ws localhost 7545 当进程完成时 我向它发送一个 SIGTERM 它不会退出 而是永远挂起 没有控制台输出 我在
  • 有没有办法查看 XMLHttpRequest 检索到的最终 URL?

    我正在执行重定向的 AJAX 下载 我想知道请求重定向到的最终目标 URL 我正在使用 jQuery 但也可以访问底层的 XMLHttpRequest 有谁知道如何获取最终 URL 看来我需要让最终目标将其 URL 插入标头或响应正文中的已
  • 如何使 Chart JS 响应式?

    我正在使用 Chart js 和 Twitter Bootstrap 模板 如果我没有提及画布的高度和宽度 则图表的尺寸不正确 但如果我指定宽度和高度 那么图表就不会响应 我该如何解决这个问题 Chart js 有一个属性 响应式 您可以通
  • Bash:从 HTTP 响应中删除标头

    如果我有一些包含 HTTP 标头和正文的文本 例如 HTTP 1 1 200 OK Cache Control public max age 38 Content Type text html charset utf 8 Expires F
  • create_task = asyncio.async:语法错误:语法无效

    我正在为 Discord 创建一个机器人 我刚刚编写了这个简单的代码 import discord TOKEN token client discord Client client event async def on ready prin
  • WidgetsFlutterBinding.ensureInitialized() 的作用是什么?

    我正在尝试将 Firebase 包与以下代码行一起使用 我很想知道这行代码到底做了什么 官方文档对我没有太大帮助 有人可以帮我解释一下吗 你必须这样使用它 void main async WidgetsFlutterBinding ensu
  • 车辆牌照检测有哪些好的算法? [关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 背景 对于我在大学的期末项目 我正在开发一个车辆牌照检测应用程序 我认为自己是一名中级程序员 但是我的数学知识缺乏中学以上的知识 这使
  • App Store 版本号 - 更改方案/最佳实践

    我们正在考虑更改 iOS 应用程序下一个版本中的版本号 从使用传统的 Major Minor Patch 版本号方案改为使用基于日期的方案 例如 2012 month patch 以更好地向用户反映当前版本的版本号 该应用程序 Apple
  • 如何在 d3.axis.tickFormat 中换行?

    我想编写一个函数 返回带有两行文本的刻度标签 正如我所看到的 svg 文本标签用于文本标签 有没有办法在那里添加 tspan 或者其他什么 您可以访问由axis Demo http jsfiddle net k6b9j 3 d3 selec
  • Unity 3D 在一段时间内平滑地旋转对象

    我正在编写一个游戏 每次节拍器跳动时 立方体都必须围绕自身平滑旋转 90 度 每次节拍器跳动时 我的方法都会调用一个协程 IEnumerator moveCoroutine if isCollided canRotate for float
  • Unity Jenkins Android Gradle 任务:mergeReleaseResources 失败,命令行工作正常

    我正在尝试设置 Jenkins 服务器以自动构建 Unity 但出现 gradle 错误 使用命令行构建工作正常 但如果尝试使用 Jenkins 则会失败 Logs 失败 构建失败并出现异常 什么地方出了错 任务 mergeReleaseR
  • iOS 中的 URL 解码

    我正在使用 Swift 1 2 开发我的 iPhone 应用程序 并且正在与 http Web 服务进行通信 我得到的响应是查询字符串格式 键值对 和 URL 编码 Net 我可以获得响应 但正在寻找使用 Swift 进行解码的正确方法 响
  • Python 处理 URL 的用户名和密码

    搞乱Python 我正在尝试使用它https updates opendns com nic update hostname https updates opendns com nic update hostname 当您访问 URL 时
  • 如何让你的java应用程序自行重启[重复]

    这个问题在这里已经有答案了 我想实施reset我的应用程序中的功能可以清理一些目录 复制文件等 然后为了完成该过程 我需要重新启动它 如何让应用程序自行重新运行 我认为打开第二个实例并关闭这个实例就足够了 尽管这不是真正的重启 我的应用程序
  • 在 Objective-C 中解码 Base64 字符串 [关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi
  • 编写Python代码来计算几何级数

    我对编程和 Python 很陌生 我需要帮助编码一个几何级数 该级数应该计算级数 1 2 4 8 16 这是我到目前为止所拥有的 def work calc days worked n temp int 1 if days worked l
  • 如果 PowerShell 中的环境变量不存在,如何设置它?

    我很惊讶在谷歌搜索一段时间后我没有得到这种常见情况的答案 如果环境变量不存在 如何在 PowerShell 中设置它 下面的代码定义了环境变量FOO对于当前进程 如果尚不存在 if null eq env FOO env FOO bar I