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?
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"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With