programing

레지스트리 값이 있는지 테스트

css3 2023. 9. 2. 08:43

레지스트리 값이 있는지 테스트

PowerShell 스크립트에서 스크립트를 실행하는 각 요소에 대해 하나의 레지스트리 항목을 만들고 각 요소에 대한 추가 정보를 레지스트리에 저장하려고 합니다(선택적 매개 변수를 한 번 지정한 경우 나중에 기본적으로 해당 매개 변수를 사용합니다).

제가 직면한 문제는 테스트-레지스트리 값을 수행해야 하는데(예: 주석 참조), 트릭을 수행하지 않는 것 같습니다(항목이 존재하더라도 false를 반환함).저는 "그 위에 건설"하려고 노력했고, 제가 생각해낸 것은 다음과 같습니다.

Function Test-RegistryValue($regkey, $name) 
{
    try
    {
        $exists = Get-ItemProperty $regkey $name -ErrorAction SilentlyContinue
        Write-Host "Test-RegistryValue: $exists"
        if (($exists -eq $null) -or ($exists.Length -eq 0))
        {
            return $false
        }
        else
        {
            return $true
        }
    }
    catch
    {
        return $false
    }
}

안타깝게도 레지스트리 키에서 항상 일부(첫 번째?) 값을 선택하는 것처럼 보이기 때문에 필요한 작업도 수행하지 못합니다.

이거 어떻게 하는지 아는 사람?관리 코드를 작성하는 것이 너무 많은 것 같습니다.

개인적으로, 저는 오류를 뱉을 가능성이 있는 테스트 기능을 좋아하지 않기 때문에, 제가 할 일은 다음과 같습니다.이 기능은 레지스트리 키 목록을 필터링하여 특정 키가 있는 레지스트리 키만 유지하는 데 사용할 수 있는 필터 역할도 합니다.

Function Test-RegistryValue {
    param(
        [Alias("PSPath")]
        [Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [String]$Path
        ,
        [Parameter(Position = 1, Mandatory = $true)]
        [String]$Name
        ,
        [Switch]$PassThru
    ) 

    process {
        if (Test-Path $Path) {
            $Key = Get-Item -LiteralPath $Path
            if ($Key.GetValue($Name, $null) -ne $null) {
                if ($PassThru) {
                    Get-ItemProperty $Path $Name
                } else {
                    $true
                }
            } else {
                $false
            }
        } else {
            $false
        }
    }
}

레지스트리 값이 있는지 테스트하는 가장 좋은 방법은 레지스트리 값의 존재 여부를 테스트하는 입니다.이것은 비록 읽기가 조금 어렵더라도 한 줄로 된 것입니다.

(Get-ItemProperty $regkey).PSObject.Properties.Name -contains $name

실제로 데이터를 조회하면 Powershell이 0을 해석하는 방법의 복잡성과 마주치게 됩니다.

Carbon PowerShell 모듈에는 이 검사를 수행하는 Test-RegistryKeyValue 기능이 있습니다. (공개:저는 Carbon의 소유자/유지관리자입니다.)

먼저 레지스트리 키가 있는지 확인해야 합니다.그런 다음 레지스트리 키에 값이 없는 경우 처리해야 합니다.여기에 있는 대부분의 예는 실제로 값의 존재 대신에 값 자체를 테스트하는 것입니다.값이 비어 있거나 null인 경우 잘못된 음수를 반환합니다.대신 값에 대한 속성이 반환된 개체에 실제로 있는지 테스트해야 합니다.Get-ItemProperty.

탄소 모듈의 코드는 다음과 같습니다.

function Test-RegistryKeyValue
{
    <#
    .SYNOPSIS
    Tests if a registry value exists.

    .DESCRIPTION
    The usual ways for checking if a registry value exists don't handle when a value simply has an empty or null value.  This function actually checks if a key has a value with a given name.

    .EXAMPLE
    Test-RegistryKeyValue -Path 'hklm:\Software\Carbon\Test' -Name 'Title'

    Returns `True` if `hklm:\Software\Carbon\Test` contains a value named 'Title'.  `False` otherwise.
    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [string]
        # The path to the registry key where the value should be set.  Will be created if it doesn't exist.
        $Path,

        [Parameter(Mandatory=$true)]
        [string]
        # The name of the value being set.
        $Name
    )

    if( -not (Test-Path -Path $Path -PathType Container) )
    {
        return $false
    }

    $properties = Get-ItemProperty -Path $Path 
    if( -not $properties )
    {
        return $false
    }

    $member = Get-Member -InputObject $properties -Name $Name
    if( $member )
    {
        return $true
    }
    else
    {
        return $false
    }

}

한 줄:

$valueExists = (Get-Item $regKeyPath -EA Ignore).Property -contains $regValueName

저는 그 기능으로 가겠습니다.Get-RegistryValue실제로 요청된 값을 얻으므로 테스트에만 사용할 수 없습니다.레지스트리 값이 null일 수 없는 한 null 결과를 결측값의 신호로 사용할 수 있습니다.순수 테스트 기능Test-RegistryValue또한 제공됩니다.

# This function just gets $true or $false
function Test-RegistryValue($path, $name)
{
    $key = Get-Item -LiteralPath $path -ErrorAction SilentlyContinue
    $key -and $null -ne $key.GetValue($name, $null)
}

# Gets the specified registry value or $null if it is missing
function Get-RegistryValue($path, $name)
{
    $key = Get-Item -LiteralPath $path -ErrorAction SilentlyContinue
    if ($key) {
        $key.GetValue($name, $null)
    }
}

# Test existing value
Test-RegistryValue HKCU:\Console FontFamily
$val = Get-RegistryValue HKCU:\Console FontFamily
if ($val -eq $null) { 'missing value' } else { $val }

# Test missing value
Test-RegistryValue HKCU:\Console missing
$val = Get-RegistryValue HKCU:\Console missing
if ($val -eq $null) { 'missing value' } else { $val }

출력:

True
54
False
missing value

공백이 있는 문자열에 문제가 있을 수 있습니다.다음은 저에게 적합한 정리된 버전입니다.

Function Test-RegistryValue($regkey, $name) {
    $exists = Get-ItemProperty -Path "$regkey" -Name "$name" -ErrorAction SilentlyContinue
    If (($exists -ne $null) -and ($exists.Length -ne 0)) {
        Return $true
    }
    Return $false
}
$regkeypath= "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" 
$value1 = (Get-ItemProperty $regkeypath -ErrorAction SilentlyContinue).Zoiper -eq $null 
If ($value1 -eq $False) {
    Write-Host "Value Exist"
} Else {
    Write-Host "The value does not exist"
}

레지스트리 값이 존재하는지 여부만 알고 싶다면 다음과 같이 하십시오.

[bool]((Get-itemproperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").PathName)

반환 예정: $true인 동안

[bool]((Get-itemproperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").ValueNotThere)

will return: $false는 그곳에 없기 때문에;)

다음과 같은 스크립트 블록으로 조정할 수 있습니다.

$CheckForRegValue = { Param([String]$KeyPath, [String]$KeyValue)
return [bool]((Get-itemproperty -Path $KeyPath).$KeyValue) }

그런 다음 그냥 다음과 같이 부릅니다.

& $CheckForRegValue "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" PathName

즐겁게 보내세요,

포키

-not속성이 없는 경우 테스트가 실행됩니다.

$prop = (Get-ItemProperty $regkey).$name
if (-not $prop)
{
   New-ItemProperty -Path $regkey -Name $name -Value "X"
}

내 버전:

Function Test-RegistryValue($Key, $Name)
{
    (Get-ChildItem (Split-Path -Parent -Path $Key) | Where-Object {$_.PSChildName -eq (Split-Path -Leaf $Key)}).Property -contains $Name
}

탐지된 예외의 정확한 텍스트와 일치하는 내 버전입니다.다른 예외이지만 이 단순한 경우에도 작동하면 true가 반환됩니다.또한 Get-ItemPropertyValue는 PS 5.0의 새로운 기능입니다.

Function Test-RegValExists($Path, $Value){
$ee = @() # Exception catcher
try{
    Get-ItemPropertyValue -Path $Path -Name $Value | Out-Null
   }
catch{$ee += $_}

    if ($ee.Exception.Message -match "Property $Value does not exist"){return $false}
else {return $true}
}

이것은 나에게 도움이 됩니다.

Function Test-RegistryValue 
{
    param($regkey, $name)
    $exists = Get-ItemProperty "$regkey\$name" -ErrorAction SilentlyContinue
    Write-Host "Test-RegistryValue: $exists"
    if (($exists -eq $null) -or ($exists.Length -eq 0))
    {
        return $false
    }
    else
    {
        return $true
    }
}

저는 위의 카본에서 방법론을 가져와서 코드를 더 작은 기능으로 간소화했는데, 이것은 저에게 매우 잘 작동합니다.

    Function Test-RegistryValue($key,$name)
    {
         if(Get-Member -InputObject (Get-ItemProperty -Path $key) -Name $name) 
         {
              return $true
         }
         return $false
    }

언급URL : https://stackoverflow.com/questions/5648931/test-if-registry-value-exists