Wie erreiche ich, dass (gci).count korrekte numerische Werte für leere Listen oder Listen mit nur einem Element zurückgibt?

Wie erreiche ich, dass (gci).count korrekte numerische Werte für leere Listen oder Listen mit nur einem Element zurückgibt?

Related:
How can I write a script to count files modified within a particular month?

When I try to get a count of items, e.g. with (gci).count to count files in a folder, PowerShell returns no output for empty lists or lists containing only one item. It works fine for lists containing multiple items, though.

Bildbeschreibung hier eingeben

How can I get PowerShell to return proper numeric values for all cases? i.e.: How can I get it to output an actual zero for empty lists, and output one for single-item lists?

My particular use case, as further described in the related question linked above, is to get a count of items in a list that results from piping a gci command's output to where.

Antwort1

This has to do with the fact that powershell, when returning an array of 1 item will simply collapse the array into that single item.

Vor Version 3 wäre das Ergebnis ein Objekt ohne die erwartete countEigenschaft gewesen und das Ergebnis wäre leer gewesen. Dies wurde "behoben" inVersion 3.

Sie haben also zwei Möglichkeiten:

  1. Upgrade auf Powershell v3
  2. Wenden Sie die folgende Problemumgehung an, bei der Sie Ihre Ergebnisse immer als Array-Typ verpacken @():

    @(gci).anzahl

verwandte Informationen