Reputation: 15329
I have a PowerShell script which processes all files in a directory, but it breaks when there is exactly 0 or 1 file in a directory, which I tracked down to Get-ChildItem
's unexpected behavior:
mkdir C:\Temp\demo1 ; cd C:\Temp\demo1
(gci).Length # 0
# (gci).GetType().Name # error: null-valued expression
ni 1.txt
(gci).Length # 0 ???
(gci).GetType().Name # FileInfo
ni 2.txt
(gci).Length # 2
(gci).GetType().Name # Object[]
ni 3.txt
(gci).Length # 3
(gci).GetType().Name # Object[]
gci
returns $null
gci
returns a FileInfo
objectgci
returns an Object[]
as expectedHow can I make Get-ChildItem
always return an Object[]
?
Upvotes: 0
Views: 551
Reputation: 15329
Simply wrap the call inside of the array operator @(...)
i.e. @(gci)
:
mkdir C:\Temp\demo2 ; cd C:\Temp\demo2
@(gci).Length # 0
@(gci).GetType().Name # Object[]
ni 1.txt
@(gci).Length # 1
@(gci).GetType().Name # Object[]
Upvotes: 4