测试是否存在注册表值

New*_*nja 37 registry powershell

在我的powershell脚本中,我为我运行脚本的每个元素创建了一个注册表项,我想在注册表中存储一些关于每个元素的附加信息(如果你指定了一个可选参数,那么默认情况下将来使用这些参数).

我遇到的问题是我需要执行Test-RegistryValue(就像这里)但它似乎没有做到这一点(即使条目存在,它也会返回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
    }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,它也没有做我需要的,因为它似乎总是从注册表项中选择一些(第一个?)值.

任何人都知道如何做到这一点?为此编写托管代码似乎太多了......

Jas*_*her 28

就个人而言,我不喜欢有机会吐出错误的测试功能,所以这就是我要做的.此函数还兼作过滤器,可用于过滤注册表项列表以仅保留具有特定键的注册表项.

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 一个bug:`$ Key.GetValue($ Name,$ null))`可以得到0或一个空字符串,即一个值存在,但`if($ Key.GetValue($ Name,$ null)))`得到错误,该脚本返回false,就好像缺少值一样.另外,我建议在任何地方使用`-LiteralPath`而不是`-Path`.任务是关于单一价值测试.请注意,`*`和`?`是注册表名称的罕见但有效的字符. (4认同)

Aar*_*sen 13

碳PowerShell的模块具有试验RegistryKeyValue功能会为你做这项检查.(披露:我是Carbon的所有者/维护者.)

您必须首先检查注册表项是否存在.然后,如果注册表项没有值,则必须处理.这里的大多数示例实际上是测试值本身,而不是值的存在.如果值为空或为null,则将返回错误否定.相反,您必须测试该值的属性是否实际存在于返回的对象上Get-ItemProperty.

以下是Carbon模块中的代码:

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
    }

}
Run Code Online (Sandbox Code Playgroud)


Bro*_*onx 7

单线:

$valueExists = (Get-Item $regKeyPath -EA Ignore).Property -contains $regValueName
Run Code Online (Sandbox Code Playgroud)


Pau*_*ams 7

测试注册表值是否存在的最佳方法就是这样做- 测试其存在。 即使很难阅读,这也是单行的。

PS C:>(获取项属性$ regkey).PSObject.Properties.Name-包含$ name

如果您实际查找其数据,那么您将遇到Powershell如何解释0的复杂情况。

  • 如果注册表路径不存在,此示例代码会给您一个异常。如果 reg 键不存在,解决方案最好只得到 $false,而不是部分得到异常。 (2认同)

Rom*_*min 6

我会去的功能Get-RegistryValue。实际上,它获取请求的值(以便它不仅可以用于测试)。至于注册表值不能为空,我们可以将空结果用作缺少值的标志。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 }
Run Code Online (Sandbox Code Playgroud)

输出:

True
54
False
missing value
Run Code Online (Sandbox Code Playgroud)


Bac*_*its 5

可能是字符串有空格的问题.这是一个适合我的清理版本:

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
}
Run Code Online (Sandbox Code Playgroud)