Directly Referencing Properties in Powershell 2.0

↘锁芯ラ 提交于 2020-01-21 20:41: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 would not return the value of my match in v2.0 but would in v4.0 where I originally wrote it.

($log | Select-String "\[CIsoCreator\] Creating iso file" -AllMatches | Select-Object -ExpandProperty line -Last 1 | Select-String "([A-Z]\:)(.*\\)*.*\.iso").matches.value

After trying a few things I ended up with this which does return as expected.

($log | Select-String "\[CIsoCreator\] Creating iso file" -AllMatches | Select-Object -ExpandProperty line -Last 1 | Select-String "([A-Z]\:)(.*\\)*.*\.iso").matches | select -expandproperty value

It seems to me there are some different rules in v2.0 that govern when you can directly reference properties but I have been unable to find a mention of this.

Does anyone have some insight in how this works between versions?


回答1:


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


来源:https://stackoverflow.com/questions/50117973/directly-referencing-properties-in-powershell-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!