首页 > 解决方案 > 如何在 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.FileInfoPowerShell 2 中的对象添加可索引性,因为它存在于 PowerShell 5 中?或者至少,Get-Item在 PowerShell 2 中,一种优雅的方式来遍历它何时只返回一个项目的结果?

标签: powershellpowershell-2.0powershell-5.0

解决方案


推荐阅读