测试注册表值是否存在 [英] Test if registry value exists

查看:47
本文介绍了测试注册表值是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 powershell 脚本中,我正在为运行脚本的每个元素创建一个注册表项,我想在注册表中存储有关每个元素的一些附加信息(如果您指定了一次可选参数,则默认情况下在未来).

In my powershell script I'm creating one registry entry for each element I run script on and I would like to store some additional info about each element in registry (if you specify optional parameters once then by default use those params in the future).

我遇到的问题是我需要执行Test-RegistryValue(比如here--see comment) 但它似乎并没有做到这一点(即使条目存在,它也会返回 false).我试图建立在它之上",但我唯一想到的是:

The problem I've encountered is that I need to perform Test-RegistryValue (like here--see comment) but it doesn't seem to do the trick (it returns false even if entry exists). I tried to "build on top of it" and only thing I came up is this:

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
    }
}

不幸的是,这也不能满足我的需求,因为它似乎总是从注册表项中选择一些(第一个?)值.

That unfortunately also doesn't do what I need as it seems it always selects some (first?) value from the registry key.

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

Anyone has idea how to do this? It just seems too much to write managed code for this...

推荐答案

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

Personally, I do not like test functions having a chance of spitting out errors, so here is what I would do. This function also doubles as a filter that you can use to filter a list of registry keys to only keep the ones that have a certain key.

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
        }
    }
}

这篇关于测试注册表值是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆