1

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? I.e. 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.

4 Answers 4

2

You can force an array to always return:

@(Get-Item *.txt)
Sign up to request clarification or add additional context in comments.

Comments

0

Use ForEach-Object

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

Comments

0

One way to insure the result will always be an array is to wrap the expression in @():

@(Get-Item *.txt)

Comments

0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.