14

It seems Get-ChildItem returns a single object instead of an array of one object if it only finds one item. For example this returns 5:

$files = Get-ChildItem -Filter "e*.txt"
$files.length

But the following should return 1 but returns 61321:

$files = Get-ChildItem -Filter "exact.txt"
$files.length

The 61321 is the size in bytes of the file exact.txt.

How can we consistently check if there were files found?

1 Answer 1

16

It is a "feature" of Get-ChildItem that it won't return an array with one item but instead the single object. To force an array append @ as in:

$files = @(Get-ChildItem -Filter "e*.txt")

Alternatively if you just want to check if there are NO files you can do:

$files = Get-ChildItem -Filter "exact.txt"
if (!$files) {"No Files"}
Sign up to request clarification or add additional context in comments.

2 Comments

Note, if Get-ChildItem returns $null you will still end up with an array with 1 item in it: $files[0] -eq $null will be true! You will not get an empty array with length 0. See issue here: stackoverflow.com/questions/40523767/…
I cannot reproduce that. @(Get-ChildItem -Filter Foo).Count returns 0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.