In PowerShell 2, you are not able to index into System.IO.FileInfo
objects as you are in PowerShell 5. For example, in PowerShell 5, you can do:
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
However, in PowerShell 2, the same behaves very differently:
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
This makes writing backwards-compatible scripts difficult. Is there a simple way to add indexability to the System.IO.FileInfo
object in PowerShell 2 as it exists in PowerShell 5? Or at the very least, an elegant way to loop through the results of Get-Item
when it only returns one item, in PowerShell 2?