1

I'm trying to write a fuction that returns [string[]] from a powershell function. But it always returns a generic object intead...

function MyGetFiles {   
    [OutputType('string[]')]
    [CmdletBinding()]
    param([string]$filter)  
    
    $found = New-Object -TypeName System.Collections.Generic.List[System.String]
    $cwd = (Get-Location).Path
    
    [string[]]$fileEntries = [IO.Directory]::GetFiles($cwd);       
    
    foreach ($file in $fileEntries) {
        if ($file -match $filter) {
            #write-host "FILE:" $file
            $found.Add($file)
        }
    }
    
    $arr= [string[]]$found.ToArray()
    $arr.GetType() | out-host
    
    return $arr
}

$wlf = MyGetFiles "\.wlf`$"

$wlf.GetType() | out-host

$wlf.Count

Script Output:

True     True     String[]    System.Array

True     True     String      System.Object

Error : The property 'Count' cannot be found on this object. Verify that the property exists.
At C:\Users\xx\Desktop\script.ps1:1675 char:1

Also, does anybody know how to get out-host to be the default instead of always pipeling to out-host?

10
  • In short: PowerShell by default enumerates collections that you output from a function (whether you output them implicitly or via a return statement), i.e. it streams (outputs) the collection elements one by one. To output a collection as a whole, use , $collection (sic) or, more explicitly but less efficiently, Write-Output -NoEnumerate $collection. See the linked duplicates for details. Commented Oct 29, 2021 at 20:13
  • As for your second question: Out-Host is the default - you don't need to use it explicitly, unless you explicitly want to bypass the success output stream (pipeline). If this explanation isn't enough, please ask a new question. Commented Oct 29, 2021 at 20:16
  • I didn't understand the questions that you use to mark mine as a dupicate... does that mean i just need to add a comma before my return? Example: "return , $arr" Commented Oct 29, 2021 at 20:18
  • what if your out-host isn't the default? Commented Oct 29, 2021 at 20:19
  • yes, return , $arr is correct. But note that, in general, return $var is just syntactic sugar for $var; return - you only need return to unconditionally exit the scope, not for producing output. Commented Oct 29, 2021 at 20:21

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.