简体   繁体   中英

Powershell Get-Item Object or Array

In a directory i do

Get-Item *.txt

When there is one .txt file inside the directory it returns a System.IO.FileSystemInfo

When there are more .txt files it returns a System.Array

What is the best way to handle this inconsistency? Ie how do i find out if the function returned an object or an array. Or even better, is there a way that Get-Item always returns an array?

I want to pass the result into an other function. This function expects an array of System.IO.FileSystemInfo objects.

您可以强制数组始终返回:

@(Get-Item *.txt)

Use ForEach-Object

Get-Item *.txt | ForEach-Object {
    # Do stuff
    $_   # this represents the "current" object
}

确保结果始终是数组的一种方法是将表达式包装在@()中:

@(Get-Item *.txt)

Alternately , if you are holding the result in a variable for use later, just specify an [array]

[array]$list = Get-Item *.txt

This is useful if you want (eg) $list.count which only works with an array. Otherwise you end up with code like:

if ( $result -eq $null) {
  $count = 0
} elseif ($list -isnot [array]) {
  $count = 1
} else {
  $count = $result.count
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM