PowerShell에 env 변수가 없으면 어떻게 설정합니까?
구글 검색을 한 후에 이 흔한 시나리오에 대한 답을 얻지 못한 것이 놀랍습니다.
환경 변수가 존재하지 않는 경우 의 환경 변수를 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
Null 병합 연산자가 있는 PowerShell(Core) 7.1+에서는 다음과 같이 단순화할 수 있습니다.
$env:FOO ??= 'bar'
문서:
환경 변수는 정의에 따라 문자열입니다.지정된 환경 변수가 정의되었지만 값이 없는 경우 해당 값은 빈 문자열(''
보다는 )보다는$null
. 따라서 다음과 비교해 볼 수 있습니다.$null
정의되지 않은 환경 변수와 정의되었지만 값이 없는 환경 변수를 구별하는 데 사용할 수 있습니다.그러나 PowerShell /에서 환경 변수에 할당하는 것에 유의하십시오.NET은 다음을 구분하지 않습니다.$null
그리고.''
, 둘 중 하나의 값을 사용하면 대상 환경 변수의 정의를 해제(제거)할 수 있습니다.cmd.exe
set FOO=
δ/δ δ의 가 나타남FOO
대화상자(, GUI ( 을 )를 통해 접근 )sysdm.cpl
)에서는 빈 문자열로 변수를 정의할 수도 없습니다.그러나 Windows API()SetEnvironmentVariable
에서는 빈 문자열을 포함하는 환경 변수를 만들 수 있습니다.
플랫폼에서는 빈 POSIX 셸(스열는빈열브환며셸예도s브환셸(예nx:e스(열s며,e-o,-se :bash
그리고./bin/sh
) - PowerShell과 달리 - 또한 생성할 수 있습니다(예:export FOO=
환경 변수 정의 및 조회는 Windows와는 달리 Unix에서는 대소문자를 구분합니다.
: 위에 따라 ( : 가 에 된 로 된 ($env:FOO = ...
), 현재 프로세스와 생성된 Thanks, PetSerAl 모든 자식 프로세스에 대해서만 존재합니다.
다음은 주로 안스가르 위처스가 기여했고 마티아스 R이 보충했습니다. 제센:
Windows에서[*] 환경 변수를 지속적으로 정의하려면 클래스의 정적 메서드를 사용해야 합니다.
# user environment
[Environment]::SetEnvironmentVariable('FOO', 'bar', 'User')
# system environment (requires admin privileges)
[Environment]::SetEnvironmentVariable('FOO', 'bar', 'Machine')
이러한 정의는 향후 세션(프로세스)에서 적용되므로 현재 프로세스에 대한 변수도 정의하려면 다음을 실행합니다.$env:FOO = 'bar'
게다가, 이것은 사실상 와 같습니다.[Environment]::SetEnvironmentVariable('FOO', 'bar', 'Process')
.
사용시[Environment]::SetEnvironmentVariable()
와 함께User
아니면Machine
, 메시지가 다른 응용프로그램에 전송되어 변경사항을 통지합니다(이러한 통지에 응답하는 응용프로그램은 거의 없음).
목표물을 목표물로 할 때는 적용되지 않습니다.Process
(또는 할당할 때)$env:FOO
), 다른 응용 프로그램(프로그램)은 어쨌든 변수를 볼 수 없기 때문입니다.
참고 항목:환경 변수 생성 및 수정(TechNet 기사).
[*] 유닉스 계열 플랫폼에서는 영구 범위를 목표로 -User
아니면Machine
- 현재 조용히 무시되고 있습니다.NET(Core) 7, 그리고 영구 환경 변수 정의에 대한 이러한 비지원은 유닉스 플랫폼 전반에 걸쳐 통일된 메커니즘이 없다는 점을 고려할 때 변경될 가능성이 적습니다.
코드
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."
}
- 함수 Set-Persistent EnvironmentVariable 실제 공정 및 시스템에서 변수/값을 설정합니다.이 함수는 Set-LocalEnvironmentVariable 함수를 호출하여 프로세스 범위 변수를 설정하고 시스템 범위의 설정 변수에 대한 작업을 수행합니다.
Windows에서는 다음을 사용할 수 있습니다.
- [환경]::SetEnvironmentVariable시스템 범위, 사용자 또는 시스템이 Linux 또는 MacOS에서 작동하지 않음
- setx 명령어
Linux의 경우 export VARALY_NAME=Smooth 값을 ~/.smooth_profile 파일에 추가할 수 있습니다.새 bash 터미널의 경우 프로세스에서 ~/.bash_profile에 위치한 지침을 실행합니다.
Linux와 유사한 MacOS에서 zsh 터미널이 있는 경우 파일은 .zprofile이고, 기본 터미널이 bash이면 파일은 .bash_profile입니다.당신이 원한다면 내 함수 코드에 기본 단말기 감지 기능을 추가해야 합니다.기본 터미널은 zsh라고 가정합니다.
- 함수 Set-LocalEnvironmentVariable 실제 공정에서 변수/값을 설정합니다.Drive env: 사용하기.
예
#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
산출량
참고문헌
환경 변수 확인
ZSH: .zprofile, .zshrc, .zlogin - 어디로거지가는?
PowerShell에 환경 변수가 없는 경우 다음 코드를 사용하여 환경 변수를 설정할 수 있습니다.
if (!(Test-Path -Path Env:VAR_NAME)) {
New-Item -Path Env:VAR_NAME -Value "VAR_VALUE"
}
VAR_NAME을 환경 변수 이름으로, VAR_VALUE를 원하는 값으로 바꿉니다.
언급URL : https://stackoverflow.com/questions/38928342/how-do-i-set-an-env-variable-in-powershell-if-it-doesnt-exist
'sourcecode' 카테고리의 다른 글
GDB가 16진수 모드에서 모든 값을 출력하도록 하는 방법은? (0) | 2023.09.21 |
---|---|
WebMethod에서 발신자의 IP 주소를 얻으려면 어떻게 해야 합니까? (0) | 2023.09.21 |
word press를 mariadb(도커)에 연결할 수 없습니다. (0) | 2023.09.16 |
Oracle Storeed Procedure에서 두 개의 반환 값을 가져오는 방법 (0) | 2023.09.16 |
Relationship between JDBC sessions and Oracle processes (0) | 2023.09.16 |