|
Re: strange PowerShell pipe semantics Mainly because powershell is targeted against administrators and not
programers. When you are administring somethiing, it's considered to be
more natural not to force user to put array operator if only one value
returned. Remember, that it's assumed that you are entering your
commands from the command line, and the goal is to let you type as
little as possible. Similar reason for returning $null and not an empty
array. This way the result can be easily used in a conditional
expression, because $null is interpreted as $false.
Please note that I'm not advocating this approach, I'm just passing on
the knowledge =)
Jason Mobarak wrote:
> Hello --
>
> Can anyone explain why PowerShell has these semantics:
>
> ---8<---
>
> function Write-Type ($o) {
> if ( $o -eq $null ) {
> Write-Host "Null"
> } else {
> Write-Host $o.GetType().Name
> }
> }
>
> $list = @()
> Write-Type $list # Object[]
>
> $result = $list | %{ $_ }
> Write-Type $result # Null
>
> $list = @(1)
> Write-Type $list # Object[]
>
> $result = $list | %{ $_ }
> Write-Type $result # Int32
>
> $list = @(1,2)
> Write-Type $list # Object[]
>
> $result = $list | %{ $_ }
> Write-Type $result # Object[]
>
> --->8---
>
> ...I would argue that an operation on a list should result in a list --
> unless it's specifically a conversion operation. I know how to force
> PowerShell to return a list but the semantics of the above seem strange,
> why would PowerShell return different types based on the contents of the
> list?
>
> Thanks,
> -- Jason |