MicrosoftDocs / PowerShell-Docs

The official PowerShell documentation sources
https://learn.microsoft.com/powershell
Other
1.97k stars 1.56k forks source link

Create an about_Type_Conversions conceptual help topic that describes PowerShell's unusually flexible and automatic type conversions #10688

Open mklement0 opened 10 months ago

mklement0 commented 10 months ago

Prerequisites

PowerShell Version

5.1, 7.2, 7.3, 7.4

Summary

PowerShell is unusually flexible with respect to type conversions, both explicit and implicit ones; while the latter ones are usually helpful, there are pitfalls, especially for users coming from languages with stricter type handling.

It would be helpful to systematically describe both how explicit and especially implicit type conversions (coercions) work in PowerShell.

Below is what I have gleaned from my own experience and experiments.

Details

Type coercions (conversions) performed by PowerShell's operators:

Proposed Content Type

About Topic

Proposed Title

about_Type_Conversions

Related Articles

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Operators

mikeclayton commented 9 months ago

A couple of other cases where PowerShell's unrelenting attempts to convert function parameters into something that an overload supports give surprising results:

sou
c

d
s
in

ion

(PowerShell Core returns the "expected" result because the underlying dotnet core has additional overloads and so targets string[] Split(string separator, System.StringSplitOptions options = System.StringSplitOptions.None) instead.

See https://stackoverflow.com/questions/76241804/how-does-powershell-split-consecutive-strings-not-a-single-letter for this issue

The workaround is to wrap $bytes in an outer array ($guid = new-object System.Guid(@(, $bytes))) so PowerShell looks for constructor with parameters that match the contents of the outer array - the first item of which is our original Byte[] instance and that matches the Guid(Byte[]] constructor.

See https://stackoverflow.com/questions/73223637/passing-an-array-parameter-value for this issue

mklement0 commented 9 months ago

Thanks, @mikeclayton.