如果PowerShell中没有';不存在?

如果PowerShell中没有';不存在?,powershell,environment-variables,Powershell,Environment Variables,我很惊讶,在谷歌搜索了一段时间后,我没有得到这个常见场景的答案 如果PowerShell中的环境变量不存在,如何在PowerShell中设置它?以下代码定义了环境变量FOO,如果它还不存在 if (-not (Test-Path env:FOO)) { $env:FOO = 'bar' } 注意:此新定义的环境变量仅适用于当前进程及其创建的任何子进程(例如,当您从ISE启动新的PowerShell会话时)。谢谢 以下主要由以下人员提供,并由以下人员补充: 在Windows[*]上,如果要持续定

我很惊讶,在谷歌搜索了一段时间后,我没有得到这个常见场景的答案


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

以下代码定义了环境变量
FOO
,如果它还不存在

if (-not (Test-Path env:FOO)) { $env:FOO = 'bar' }
注意:此新定义的环境变量仅适用于当前进程及其创建的任何子进程(例如,当您从ISE启动新的PowerShell会话时)。谢谢

以下主要由以下人员提供,并由以下人员补充:

在Windows[*]上,如果要持续定义环境变量,则需要使用类的静态方法:

请注意,这些定义将在将来的会话(进程)中生效,因此为了也定义当前进程的变量,另外运行
$env:FOO='bar'
,这实际上与
[Environment]:SetEnvironmentVariable('FOO','bar','process')
相同

当使用
[Environment]:SetEnvironmentVariable()
用户
机器
一起使用时,会向其他应用程序发送一条消息,通知其更改(尽管很少有应用程序对此类通知作出反应)。
当定位
进程
(或分配给
$env:FOO
)时,这不适用,因为其他应用程序(进程)无论如何都看不到该变量


[*]在类Unix平台上,从.NET(Core)5开始,针对持久作用域
用户
机器
的尝试被悄悄地忽略了,鉴于Unix平台之间缺乏统一的机制,这种对定义持久环境变量的不支持不太可能改变。

function Set-LocalEnvironmentVariable {
    param (
        [Parameter()]
        [System.String]
        $Name,

        [Parameter()]
        [System.String]
        $Value,

        [Parameter()]
        [Switch]
        $Append
    )
    if($Append.IsPresent)
    {
        if(Test-Path "env:$Name")
        {
            $Value = (Get-Item "env:$Name").Value + $Value
        }
    }
    Set-Item env:$Name -Value "$value" | Out-Null
}

function Set-PersistentEnvironmentVariable {
    param (
        [Parameter()]
        [System.String]
        $Name,
    
        [Parameter()]
        [System.String]
        $Value,
    
        [Parameter()]
        [Switch]
        $Append        
    )
    
    Set-LocalEnvironmentVariable -Name $Name -Value $Value -Append:$Append
    if ($Append.IsPresent) {
        $value = (Get-Item "env:$Name").Value
    }
    
    if ($IsWindows) {
        setx "$Name" "$Value" | Out-Null
        return
    }
    $pattern = "\s*export[ \t]+$Name=[\w]*[ \t]*>[ \t]*\/dev\/null[ \t]*;[ \t]*#[ \t]*$Name\s*"
    
    if ($IsLinux) {
        $file = "~/.bash_profile"
        $content = (Get-Content "$file" -ErrorAction Ignore -Raw) + [System.String]::Empty
        $content = [System.Text.RegularExpressions.Regex]::Replace($content, $pattern, [String]::Empty);
        $content += [System.Environment]::NewLine + [System.Environment]::NewLine + "export $Name=$Value > /dev/null ;  # $Name"
        Set-Content "$file" -Value $content -Force
        return
    }
    if ($IsMacOS) {
        $file = "~/.zprofile"
        $content = (Get-Content "$file" -ErrorAction Ignore -Raw) + [System.String]::Empty
        $content = [System.Text.RegularExpressions.Regex]::Replace($content, $pattern, [String]::Empty);
        $content += [System.Environment]::NewLine + [System.Environment]::NewLine + "export $Name=$Value > /dev/null ;  # $Name"
        Set-Content "$file" -Value $content -Force
        return
    }
    throw "Invalid platform."
}

  • 函数集PersistentEnvironmentVariable 在实际过程和系统中设置变量/值。此函数调用Set-LocalEnvironmentVariable函数来设置进程范围变量,并为机器范围内的设置变量执行任务
在Windows上,您可以使用:

  • 对于机器范围,用户或机器不能在Linux或MacOS上工作
  • 命令
在Linux上,我们可以将导出变量名=变量值添加到文件~/.bash\u profile。对于新的bash终端,进程将执行位于~/.bash\u概要文件中的这些指令

在MacOS上类似于Linux,但如果您有zsh终端,则文件为.zprofile,如果默认终端为bash,则文件为.bash\u profile。在我的函数代码中,如果您愿意,我们需要添加默认终端的检测。我假设默认的终端是zsh

  • 函数集LocalEnvironmentVariable 在实际过程中设置变量/值。使用驱动器环境:

示例

#Set "Jo" value to variable "NameX", this value is accesible in current process and subprocesses, this value is accessible in new opened terminal.
Set-PersistentEnvironmentVariable -Name "NameX" -Value "Jo"; Write-Host $env:NameX

#Append value "ma" to current value of variable "NameX", this value is accesible in current process and subprocesses, this value is accessible in new opened terminal.
Set-PersistentEnvironmentVariable -Name "NameX" -Value "ma" -Append; Write-Host $env:NameX

#Set ".JomaProfile" value to variable "ProfileX", this value is accesible in current process/subprocess.
Set-LocalEnvironmentVariable "ProfileX" ".JomaProfile"; Write-Host $env:ProfileX



输出

Windows 10

Ubuntu WSL


参考资料

#Set "Jo" value to variable "NameX", this value is accesible in current process and subprocesses, this value is accessible in new opened terminal.
Set-PersistentEnvironmentVariable -Name "NameX" -Value "Jo"; Write-Host $env:NameX

#Append value "ma" to current value of variable "NameX", this value is accesible in current process and subprocesses, this value is accessible in new opened terminal.
Set-PersistentEnvironmentVariable -Name "NameX" -Value "ma" -Append; Write-Host $env:NameX

#Set ".JomaProfile" value to variable "ProfileX", this value is accesible in current process/subprocess.
Set-LocalEnvironmentVariable "ProfileX" ".JomaProfile"; Write-Host $env:ProfileX


检查