powershell - 如何在 PowerShell 2 中索引单个 System.IO.FileInfo 对象
问题描述
在 PowerShell 2 中,您无法System.IO.FileInfo
像在 PowerShell 5 中那样对对象进行索引。例如,在 PowerShell 5 中,您可以执行以下操作:
PS C:\test> mkdir test
Directory: C:\test\test
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 7/20/2018 18:10 test
PS C:\test> echo "test" > test\test
PS C:\test> $foo = (Get-Item test\*)
PS C:\test> $foo.Count
1
PS C:\test> $foo[0]
Directory: C:\test\test
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 7/20/2018 18:10 14 test
PS C:\test> $foo[0].Name
test
然而,在 PowerShell 2 中,同样的行为非常不同:
PS C:\test> mkdir test
Directory: C:\test
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 7/20/2018 6:14 PM test
PS C:\test> echo "test" > test\test
PS C:\test> $foo = (Get-Item test\*)
PS C:\test> $foo.Count
PS C:\test> $foo[0]
Unable to index into an object of type System.IO.FileInfo.
At line:1 char:6
+ $foo[ <<<< 0]
+ CategoryInfo : InvalidOperation: (0:Int32) [], RuntimeException
+ FullyQualifiedErrorId : CannotIndex
PS C:\test> $foo[0].name
Unable to index into an object of type System.IO.FileInfo.
At line:1 char:6
+ $foo[ <<<< 0].name
+ CategoryInfo : InvalidOperation: (0:Int32) [], RuntimeException
+ FullyQualifiedErrorId : CannotIndex
这使得编写向后兼容的脚本变得困难。是否有一种简单的方法可以为System.IO.FileInfo
PowerShell 2 中的对象添加可索引性,因为它存在于 PowerShell 5 中?或者至少,Get-Item
在 PowerShell 2 中,一种优雅的方式来遍历它何时只返回一个项目的结果?
解决方案
推荐阅读
- amazon-web-services - AWS EC2 Autoscaling 平均 CPU 利用率与 Grafana CPU 利用率
- .net-core - UHint for Kendo Dropdownlist in Grid on Partial View 失败.Net Core
- css - 在 CSS 文件中进行语义搜索
- html - 左边距不与自动合并
- .net - 如何修复 BackgroundWorker1 不做他的工作?
- javascript - React - 动态设置状态,无需硬编码关键字段
- javascript - 为什么 navigator.mediaDevice 只能在 localhost:9090 上正常工作?
- unit-testing - 关于质量保证方面的软件开发有什么建议吗?
- python - 计算千个素数
- scrapy - 在scrapy itemloader中更改响应