4

Why does (gci c:\ddd).count on an Empty folder not return 0 but "nothing"

I just get an Error "You cannot call a method on a null-valued expression." When my count-condition does not match.

What do i need to "get" the zero to prevent the exception?

icnivad
  • 2,231
  • 8
  • 29
  • 35

1 Answers1

7

Use the operator @() to make sure that the result is an array, including empty or containing a single item:

@(gci c:\ddd).count

Commands may return: 1) a collection; 2) a single object; 3) null. Your case is 3. Calling .Count on null (case 3) or on an object that does not have a property Count (case 2) gets nothing or may fail, for example, with strict mode enabled Set-StrictMode -Version 2.

@(...) is always an array and Count works.

Roman Kuzmin
  • 40,627
  • 11
  • 95
  • 117