programing

PowerShell에서 특정 변수가 글로벌 범위에 존재하는지 여부를 테스트하려면 어떻게 해야 합니까?

javajsp 2023. 4. 19. 22:15

PowerShell에서 특정 변수가 글로벌 범위에 존재하는지 여부를 테스트하려면 어떻게 해야 합니까?

WPF 애플리케이션의 UI 자동화에 PowerShell 스크립트를 사용하고 있습니다.일반적으로 스크립트는 글로벌 변수 값에 따라 그룹으로 실행됩니다.스크립트를 1개만 실행하고 싶을 때는 수동으로 이 변수를 설정하는 것이 조금 불편하기 때문에 이 변수를 체크하고 없으면 설정하는 방법을 찾고 있습니다.

test-path variable:\foo이 동작하지 않는 것 같습니다.아직도 다음 오류가 뜨기 때문입니다.

변수 '$global:foo'가 설정되지 않았으므로 검색할 수 없습니다.

Test-Path 는 특별한 구문과 함께 사용할 수 있습니다.

Test-Path variable:global:foo

이는 환경변수($env:foo):

Test-Path env:foo

비글로벌 변수의 경우(단,$foo인라인):

Test-Path variable:foo

편집: 아래 Stej의 답변을 사용합니다.제 자신의 (부분적으로 올바르지 않은) 것은, 참조를 위해서 아직 여기서 재현되고 있습니다.


사용할 수 있습니다.

Get-Variable foo -Scope Global

변수가 존재하지 않을 때 발생하는 오류를 트랩합니다.

개인 취향은Ignore에 걸쳐서SilentlyContinue전혀 오류가 아니기 때문입니다.우리가 예상하는 바로는$false(로) 그것을 막자Ignore(사일런트)에 배치되는 것을 방지합니다.$Error스택을 클릭합니다.

다음을 사용할 수 있습니다.

if (Get-Variable 'foo' -Scope 'Global' -ErrorAction 'Ignore') {
    $true
} else {
    $false
}

보다 간결하게:

[bool](gv foo -s global -ea ig)

다음 중 하나의 출력:

False

또는

변수가 존재하지 않을 때 발생하는 오류를 트랩할 수 있습니다.

try {
    Get-Variable foo -Scope Global -ErrorAction 'Stop'
} catch [System.Management.Automation.ItemNotFoundException] {
    Write-Warning $_
}

출력:

WARNING: Cannot find a variable with the name 'foo'.

변수를 Get-Variable 반환값에 할당한 후 null인지 확인할 수 있습니다.

$variable = Get-Variable -Name foo -Scope Global -ErrorAction SilentlyContinue

if ($variable -eq $null)
{
    Write-Host "foo does not exist"
}

# else...

변수가 "존재하기" 위해서는 변수를 할당해야 합니다.예를 들어 다음과 같습니다.

$global:foo = $null

$variable = Get-Variable -Name foo -Scope Global -ErrorAction SilentlyContinue

if ($variable -eq $null)
{
    Write-Host "foo does not exist"
}
else
{
    Write-Host "foo exists"
}

$global:bar

$variable = Get-Variable -Name bar -Scope Global -ErrorAction SilentlyContinue

if ($variable -eq $null)
{
    Write-Host "bar does not exist"
}
else
{
    Write-Host "bar exists"
}

출력:

foo exists
bar does not exist

심플:

 [boolean](get-variable "Varname" -ErrorAction SilentlyContinue)

아직까지는 이 답이 효과가 있는 것 같습니다.

좀 더 자세히 설명하자면, 제게 효과가 있었던 것은 다음과 같습니다.

Get-Variable -Name foo -Scope Global -ea SilentlyContinue | out-null

$?true 또는 false 중 하나를 반환합니다.

$myvar = if ($env:variable) { $env:variable } else { "default_value" } 

다음 작업을 수행할 수 있습니다.

$global:foo -eq $null

이것은 돌아올 것이다.$true만약$global:foo설정되지 않았습니다.

MyVariable 변수 존재 여부를 테스트합니다.부울 true 또는 false를 반환합니다.

Test-Path variable:\MyVariable

더 쉬운 방법이 있습니다.

if ($variable)
{
    Write-Host "bar exist"
}
else
{
    Write-Host "bar does not exists"
}

언급URL : https://stackoverflow.com/questions/3159949/in-powershell-how-do-i-test-whether-or-not-a-specific-variable-exists-in-global