如何使用 [Microsoft.Win32.RegistryValueKind]::TryParse

How to use [Microsoft.Win32.RegistryValueKind]::TryParse

我似乎无法 [Microsoft.Win32.RegistryValueKind]::TryParse 正常工作。我总是尝试每个解决方案 returns Cannot find an overload for "TryParse" and the argument count: "2". (or "3") 尽管它显示以下内容。

PS C:\Windows\system32> [Microsoft.Win32.RegistryValueKind]::TryParse

OverloadDefinitions                                                                                                                          
-------------------                                                                                                                          
static bool TryParse[TEnum](string value, [ref] TEnum result)                                                                                
static bool TryParse[TEnum](string value, bool ignoreCase, [ref] TEnum result)

根据我的经验,以下任何一项通常都可以正常工作。

[Microsoft.Win32.RegistryValueKind]::TryParse('dword',[ref]$Null)
[Microsoft.Win32.RegistryValueKind]::TryParse('dword',$true,[ref]$Null)

与此同时,我可以将字符串转换为 [Microsoft.Win32.RegistryValueKind],但我很好奇我做错了什么。

[Microsoft.Win32.RegistryValueKind]::TryParse() 方法本身将 return $true$false,具体取决于解析是否成功。

  • 第一个参数是要解析并转换为 RegistryValueKind enum 类型之一的 字符串 值。
  • 最后一个参数是包含所选 RegistryValueKind 类型的变量。
    该方法然后尝试将给定的字符串值转换为该注册表类型。
  • 可选地,有一个带有第二个参数的重载,您可以将其设置为 $true 以使其对给定的字符串值 case-insensitive 起作用。

示例:

[Microsoft.Win32.RegistryValueKind]::TryParse('12345', [ref][Microsoft.Win32.RegistryValueKind]::DWord)

returns 正确,因为“12345”可以转换为整数 DWord 值种类。

你也可以像这样读回解析后的值

$result = [Microsoft.Win32.RegistryValueKind]::DWord   # 4
if ([Microsoft.Win32.RegistryValueKind]::TryParse('12345', [ref]$result)) {
    Write-Host "The value can be stored as $result (DWord)"
}

无论如何,如果您打算读取注册表值并尝试确定该条目的 RegistryKind 是否正确,我认为 RegistryKey.GetValueKind() 方法会更容易使用

TryParse实际上是由System.Enum实现的,是泛型方法。 returns一个bool是否解析成功,第二个参数是一个out实际解析结果

如果您想使用 TryParse,您会遇到一些问题。

首先,除非您使用 PS 7.3 或更高版本

,否则您不能直接在 Powershell 中调用泛型方法
[System.Enum]::TryParse<Microsoft.Win32.RegistryValueKind>('DWord', [ref]$prm)

对于使用 .Net Core 或 .Net 5 的 Powershell 版本(如果有的话我不知道),您还可以使用 TryParse[=20= 的 non-generic 版本]

[System.Enum]::TryParse([Microsoft.Win32.RegistryValueKind], 'DWord', [ref]$prm)

尽管如此,在早期版本中您需要使用反射。

$arrParams =  @('DWord', $null)

$method = ([System.Enum].GetMethods() | where {($_.Name -eq "TryParse") -and ($_.GetParameters().Length -eq 2) })[0].MakeGenericMethod(@([Microsoft.Win32.RegistryValueKind]))

$method.Invoke($null, $arrParams);

$arrParams[1]

注意字符串参数是case-sensitive,因此必须是'DWord'