Directly Referencing Properties in Powershell 2.0

后端 未结 1 1719
借酒劲吻你
借酒劲吻你 2021-01-26 21:50

I encountered a bug in a script I wrote this morning where I wasn\'t getting an output from my Select-String expression. After a bit of playing I realized that this expression w

相关标签:
1条回答
  • 2021-01-26 22:29

    This is due to a change in language behavior introduced in PowerShell version 3.0 - from the "What's new in PowerShell 3.0" release notes:

    Windows PowerShell Language Enhancements

    Windows PowerShell 3.0 includes many features that are designed to make its language simpler, easier to use, and to avoid common errors. The improvements include property enumeration, count and length properties on scalar objects, new redirection operators, the $Using scope modifier, PSItem automatic variable, flexible script formatting, attributes of variables, simplified attribute arguments, numeric command names, the Stop-Parsing operator, improved array splatting, new bit operators, ordered dictionaries, PSCustomObject casting, and improved comment-based help.

    (Emphasis added by me)

    Property enumeration allows the . reference operator to resolve the properties of individual members of an array expression, even though the array itself has no such property:

    $Things = 1..3 |%{ New-Object psobject -Property @{Prop = $_} }
    $Things.Prop   # Starting with version 3.0, this outputs the array 1,2,3 
                   # In PowerShell version 2.0, this will throw an error 
                   # because [Object[]] ($Things) has no such property
    
    0 讨论(0)
提交回复
热议问题