【问题标题】:Directly Referencing Properties in Powershell 2.0Powershell 2.0 中直接引用属性
【发布时间】:2018-10-11 13:54:30
【问题描述】:

我在今天早上编写的脚本中遇到了一个错误,我没有从我的 Select-String 表达式中获得输出。玩了一会儿后,我意识到这个表达式不会返回我在 v2.0 中匹配的值,但会在我最初编写它的 v4.0 中返回。

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

在尝试了几件事后,我最终得到了这个结果,它确实按预期返回。

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

在我看来,v2.0 中有一些不同的规则来管理您何时可以直接引用属性,但我一直找不到提及这一点。

有没有人知道这在不同版本之间是如何工作的?

【问题讨论】:

标签: powershell powershell-2.0 powershell-4.0


【解决方案1】:

这是由于 PowerShell 3.0 版中引入的语言行为发生了变化 - 从 "What's new in PowerShell 3.0" release notes:

Windows PowerShell 语言增强

Windows PowerShell 3.0 包含许多旨在使其语言更简单的功能, 更易于使用,并避免常见错误。改进包括 属性枚举,标量对象的计数和长度属性, 新的重定向运算符,$Using 范围修饰符,PSItem 自动 变量,灵活的脚本格式,变量的属性, 简化的属性参数、数字命令名称、 停止解析运算符,改进的数组飞溅,新的位运算符, 有序字典、PSCustomObject 转换和改进 基于评论的帮助。

我添加的重点

属性枚举允许. 引用运算符解析数组表达式的各个成员的属性,即使数组本身没有这样的属性:

$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

【讨论】:

  • 我读过它,当时它没有意义。我刚回去仔细检查,我返回了一个长度为 1 的数组,所以这确实是问题所在。
猜你喜欢
  • 2021-02-17
  • 2021-11-03
  • 2014-06-27
  • 2020-03-28
  • 2012-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多