Home > other >  How to ALWAYS return an array from Get-ChildItem and similar functions?
How to ALWAYS return an array from Get-ChildItem and similar functions?

Time:03-02

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[]
  • For 0 items, gci returns $null
  • For 1 item, gci returns a FileInfo object
  • For 2 items, gci returns an Object[] as expected

How can I make Get-ChildItem always return an Object[]?

CodePudding user response:

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[]
  • Related