Skip to content

Commit

Permalink
Fix Get-ItemProperty to report non-terminating error for cast excep…
Browse files Browse the repository at this point in the history
  • Loading branch information
ArmaanMcleod authored Dec 27, 2024
1 parent e127345 commit b5fbe9e
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 2 deletions.
15 changes: 13 additions & 2 deletions src/System.Management.Automation/namespaces/RegistryProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1825,8 +1825,19 @@ public void GetProperty(
notePropertyName = LocalizedDefaultToken;
}

propertyResults.Properties.Add(new PSNoteProperty(notePropertyName, key.GetValue(valueName)));
valueAdded = true;
try
{
propertyResults.Properties.Add(new PSNoteProperty(notePropertyName, key.GetValue(valueName)));
valueAdded = true;
}
catch (InvalidCastException invalidCast)
{
WriteError(new ErrorRecord(
invalidCast,
invalidCast.GetType().FullName,
ErrorCategory.ReadError,
path));
}
}

key.Close();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,47 @@ Describe "Extended Registry Provider Tests" -Tags @("Feature", "RequireAdminOnWi
}
}
}

Context "Validate Get-ItemProperty Cast Exception" {
BeforeAll {
if ($IsWindows) {
$registrySubkeyPath = 'HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\badreg'

# Below will import .reg file with 64 bit integer in 32 bit DWORD
$badRegistryContent = @"
Windows Registry Editor Version 5.00
[$registrySubkeyPath]
"NoModify"=hex(4):01,00,00,00,00,00,00,00
"@

$badRegistryPath = Join-Path -Path $TestDrive -ChildPath badreg.reg
$badRegistryContent | Set-Content -Path $badRegistryPath
reg.exe import $badRegistryPath

$registryProviderSubkeyPath = 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\badreg'
}
}

It "Validate non-terminating error for cast" {
Get-ItemProperty -Path $registryProviderSubkeyPath -ErrorVariable err -ErrorAction SilentlyContinue
$err | Should -HaveCount 1
$err[0].Exception | Should -BeOfType [System.InvalidCastException]
$err[0].TargetObject | Should -BeExactly $registrySubkeyPath
$err[0].CategoryInfo.Category | Should -BeExactly 'ReadError'
$err[0].FullyQualifiedErrorId | Should -BeExactly 'System.InvalidCastException,Microsoft.PowerShell.Commands.GetItemPropertyCommand'
}

It "Validate terminating error for cast" {
{ Get-ItemProperty -Path $registryProviderSubkeyPath -ErrorAction Stop } | Should -Throw -ErrorId 'System.InvalidCastException,Microsoft.PowerShell.Commands.GetItemPropertyCommand'
}

AfterAll {
if ($IsWindows) {
reg.exe delete $registrySubkeyPath /f
}
}
}
}

} finally {
Expand Down

0 comments on commit b5fbe9e

Please sign in to comment.