diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index e1788d5996f..72d6dbbd276 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -280,7 +280,7 @@ internal static ITypeName ScanType(string typename, bool ignoreErrors) var result = parser.TypeNameRule(allowAssemblyQualifiedNames: true, firstTypeNameToken: out _); SemanticChecks.CheckArrayTypeNameDepth(result, PositionUtilities.EmptyExtent, parser); - if (!ignoreErrors && parser.ErrorList.Count > 0) + if (!ignoreErrors && result is not null && (parser.ErrorList.Count > 0 || !result.Extent.Text.Equals(typename, StringComparison.OrdinalIgnoreCase))) { result = null; } diff --git a/test/powershell/Language/Parser/Conversions.Tests.ps1 b/test/powershell/Language/Parser/Conversions.Tests.ps1 index 119f74d9a8a..f6874b1db93 100644 --- a/test/powershell/Language/Parser/Conversions.Tests.ps1 +++ b/test/powershell/Language/Parser/Conversions.Tests.ps1 @@ -78,6 +78,14 @@ Describe 'conversion syntax' -Tags "CI" { $result -join ";" | Should -Be ($Elements -join ";") } } + + It 'Should not convert invalid strings to type name using -as operator' { + 'int]whatever' -as [type] | Should -Be $null + } + + It 'Should not convert invalid strings to type name using left-hand side operator' { + {[Type] 'int]whatever'} | Should -Throw + } } Describe "Type resolution should prefer assemblies in powershell assembly cache" -Tags "Feature" {