Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell Get-ChildItem returns object not array

Tags:

arrays

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?

like image 875
Marc Avatar asked Sep 26 '16 12:09

Marc


1 Answers

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"}
like image 51
Marc Avatar answered Sep 30 '22 07:09

Marc