2016-04-22 101 views
1

当我尝试在读取注册表时使用比较运算符时,(默认)键似乎没有正确比较。默认键是字符串,但是当我比较字符串,它不匹配:当比较运算符在读取注册表时,Powershell不能识别(默认)注册表作为字符串

首先,例如注册表中创建:

  • HKCU:\ BRANCH1 \ BRANCH2
  • HKCU:\ BRANCH1 \ BRANCH2 ! (默认)= defaultValue(REG_SZ)
  • hkcu:\ branch1 \ branch2! testVal1 =测试值(REG_SZ)

如果我们再运行以下命令:

(gp HKCU:\branch1\branch2).PSObject.Properties | ? {$_.Name -notlike 'PS*'} | select Name, TypeNameOfValue, Value | ft -a 

结果:

名称TypeNameOfValue价值

---- ---- ----------- -----

(默认)System.String defaultValue

testVal1 System.String测试值

正如你所看到的,它清楚地列出了默认值作为一个字符串。那么,为什么下面的比较不起作用?

Get-ItemProperty "HKCU:\branch1\branch2" | ForEach-Object { 
    $CurrentKey = $_ 
    write-host "Looking at key $CurrentKey" 
    foreach ($PropertyName in ($CurrentKey | Get-Item).GetValueNames()) { 
    if ($CurrentKey.$PropertyName -is [string]) { 
     write-host $PropertyName with value of $CurrentKey.$PropertyName STRING! 
    } 
    else{    
     write-host $PropertyName with value of $CurrentKey.$PropertyName NOT STRING!        
    } 
} 

}

哪个给出结果:

在键@ {(默认值)=默认值寻找; testVal1 = testValue}

值NOT STRING!

testVal1的值为testValue STRING!

您将看到(默认)值输出为空(名称和值),并且不会被检测为字符串。为什么是这样?为什么我无法将默认值与STRING进行比较?

回答

0

我用teststring值创建了一个测试键。我该如何比较的值的类型名:

$test = (gp HKCU:\test\).PSObject.Properties 

if (($test.Item("teststring").TypeNameOfValue) -eq "System.String") {"yes"} else {"no"} 
+0

虽然以下工作:'如果(($ test.Item( “(默认)”)TypeNameOfValue)当量 “System.String”。)'我”无法获得“默认”名称作为变量。由于我使用发布的代码遍历注册表,名称默认值NAME在变量中被返回为“空白”而不是“(默认)”。 – MrBeatnik

+0

刚刚在我的示例中检查了foreach循环,它返回了(默认)名称和system.string值类型。 'foreach($ test in $ test){Write-Host $ row.Name,$ row.TypeNameOfValue}' –

+0

(编辑)我这样做了 - 添加了:if($ PropertyName -eq“”){$ valName = “(默认)”} else {$ valName = $ PropertyName}',然后运行if(($ test.Item($ valName).TypeNameOfValue)-eq“System.String”'这对我有效但是,你的代码看起来更好 - 我会看看我是否可以更新循环代码。谢谢 – MrBeatnik