我发现了几个示例,展示了如何获取、设置和创建注册表项及其属性和值。我需要查找注册表项属性的属性类型(双字、字符串、多字符串等)
如果我执行Get-ItemProperty
,我可以获取属性的值,如下所示:
PS C:\> Get-ItemProperty "HKLM:\SOFTWARE\MySoftware\MyKey\" -Name MyProperty
MyProperty : MyValue
PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\MySoftware\MyKey\
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\MySoftware
PSChildName : MyValue
PSDrive : HKLM
PSProvider : Microsoft.PowerShell.Core\Registry
但是,这并没有告诉我 MyProperty 的值是字符串、双字型、多字符串还是其他任何形式。我发现获取该信息的唯一方法是将其通过管道传递给 Get-Member
,因为定义告诉我它是什么类型:
PS C:\> Get-ItemProperty "HKLM:\SOFTWARE\MySoftware\MyKey\" -Name MyProperty | Get-Member
TypeName: System.Management.Automation.PSCustomObject
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
PSChildName NoteProperty string PSChildName=MyKey
PSDrive NoteProperty PSDriveInfo PSDrive=HKLM
PSParentPath NoteProperty string PSParentPath=Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\MySoftware
PSPath NoteProperty string PSPath=Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\MySoftware\MyKey\
PSProvider NoteProperty ProviderInfo PSProvider=Microsoft.PowerShell.Core\Registry
MyProperty NoteProperty string MyProperty=MyValue
然后我可以选择属性值,分割字符串并获取第一个对象,如下所示:
PS C:\> ((Get-ItemProperty "HKLM:\SOFTWARE\MySoftware\MyKey\" -Name MyProperty | Get-Member | Where-Object{$_.Name -eq "MyProperty"}).Definition -split " ")[0]
string
我验证了当我使用 DWord 属性执行此操作时,这会给出 int
,但这感觉不像查找此信息的正确方法。是否有另一种更合适或更可靠的方法来查找特定注册表项属性具有的属性类型?
编辑:我还刚刚验证了 String 和 ExpandString 都返回“string”,因此存在边缘情况,即使上述解决方案也不起作用。
最佳答案
您可以使用 .GetType()
方法获取属性的类型:
$value = (Get-ItemProperty 'HKLM:\SOFTWARE\MySoftware\MyKey' -Name MyProperty).MyProperty
$value.GetType().Name # outputs e. g. "String"
要显式测试给定类型,请使用 -is
运算符:
$value -is [string] # outputs True if $value is a string
为了了解每个注册表值类型如何映射到 PowerShell 类型,我创建了一个包含所有可能类型的值的注册表项,并运行了以下脚本:
$props = Get-ItemProperty "HKCU:\test"
$props.PSObject.Properties.Where{ -not $_.Name.StartsWith('PS') }.ForEach{
[pscustomobject]@{ 'Reg Type' = $_.Name; 'PS Type' = $_.Value.GetType() }
}
输出:
Reg Type PS Type
-------- -------
REG_DWORD System.Int32
REG_SZ System.String
REG_QWORD System.Int64
REG_BINARY System.Byte[]
REG_MULTI_SZ System.String[]
REG_EXPAND_SZ System.String
正如您所看到的,REG_SZ
和 REG_EXPAND_SZ
都映射到 System.String
,因此当您使用获取项目属性
。相反,您必须使用 .NET 方法 RegistryKey.GetValueKind()
:
$key = Get-Item 'HKLM:\SOFTWARE\MySoftware\MyKey' # $key is of type RegistryKey
$key.GetValue('MyProperty') # Output the value
$key.GetValueKind('MyProperty') # Output the registry type of the value
这将为注册表类型REG_EXPAND_SZ
输出“ExpandString”。对于其他可能的值,请参阅 RegistryValueKind
枚举。
关于Powershell如何查找注册表项属性的属性类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72373323/