0

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[]?

xjcl
  • 12,848
  • 6
  • 67
  • 89
  • Be careful, you can also get a `DirectoryInfo` if the directory contains an other directory, and Object[] may be an array of non homogenous objects. Behind the scene these CmdLets (ending with item) are a bit more complex than simple `dir` or `ls`. You can use them to work on registry, list of vars or certificates. Have a look to Get-PSProvider and Get-PSDrive. – JPBlanc Feb 26 '22 at 05:25
  • Does this answer your question? [return array of objects from Get-ChildItem -Path](https://stackoverflow.com/questions/55765010/return-array-of-objects-from-get-childitem-path), see also`about-arrays`: [The array sub-expression operator](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_arrays#the-array-sub-expression-operator) – iRon Feb 26 '22 at 07:32
  • @iRon The question title is matching, but the question content is totally different. IMO OP thought they were getting back a string instead of an object array, which is both not true and a separate issue. – xjcl Feb 26 '22 at 07:57
  • @xjcl, (I have removed the duplicate vote) eventho, I think that the [answer](https://stackoverflow.com/a/55767507/1701026) covers the title. Besides this is a [classic PowerShell gotcha (#4)](https://stackoverflow.com/a/69644807/1701026) related to the pipeline enrolling. Maybe it is indeed good to have (again?) a specific question about this but I would and more details in the answer, and have a more positive approach as some might call it *buggy* and others *magic*: You need an Object[]? Did you ask for it? The ETS will just do it for you: `[object[]](gci)` – iRon Feb 26 '22 at 08:25
  • @iRon I didn't include `[object[]](gci)` in the answer because it doesn't work if there are 0 files and `gci` returns the `$null` object – xjcl Feb 26 '22 at 08:28
  • 1
    @iRon I meant that it lead to buggy behavior in my subsequent code, I wasn't calling PS buggy. I'll rephrase it – xjcl Feb 26 '22 at 08:34

1 Answers1

4

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[]
xjcl
  • 12,848
  • 6
  • 67
  • 89