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?
returnstatement), 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.Out-Hostis 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.return , $arris correct. But note that, in general,return $varis just syntactic sugar for$var; return- you only needreturnto unconditionally exit the scope, not for producing output.