powershell - Powershell 2.0 中直接引用属性
问题描述
我在今天早上编写的脚本中遇到了一个错误,我没有从我的 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 3.0 版中引入的语言行为发生了变化 - 来自“PowerShell 3.0 中的新增功能”发行说明:
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
推荐阅读
- python - 如何修复已爬网 (403)
- sql - String_Agg 内部不同
- docker - 如何阻止“kubectl exec”的选项以及与集群上某个容器的任何其他外部连接
- r - 在函数中传递参数时出现问题
- swift - 注册时无法显示应用程序 bundleID 的自动强密码
- visual-studio-code - Visual Studio Code 上的 tflint:lint:Linting 失败
TypeError:issues.forEach 不是函数 - go - Go SDK Apache Beam:单例侧输入Singleton for int ill-defined
- python - 得到
在 0x7f6f056c2840> 错误 - mailkit - 无法连接到 SMTP 服务器
- laravel - 模型关系