Controlling the type returned by a Function in PowerShell

前端 未结 1 613
梦如初夏
梦如初夏 2021-01-15 05:09

So, I\'m trying to create a GUI for a search application using a WPF form. My form has a TextBox and ComboBox for input, and the contents are applied as a filter every time

相关标签:
1条回答
  • 2021-01-15 05:37
    • PowerShell by default enumerates collections that you output from a function (whether you output them implicitly or via a return statement)

      • To prevent that, use Write-Output -NoEnumerate or, more simply and efficiently (but more obscurely), wrap the output collection in a single-element aux. array (, $collection) - see this answer for more information.
    • In your case, you additionally need to make sure that what you're wrapping is itself always a collection, for which you can use @() or cast to [array].

    Function GetFilteredItems
    {
        $RSelect = $var_SearchRegion.SelectedValue.Content
        $PF = $var_SearchFor.Text
        $RF = If ($RSelect -eq 'All Regions') {''} Else {$RSelect}
    
        # Collect your command's output in an array-typed variable ([object[]])
        [array] $result = 
          If ($PF -eq '' -and $RF -eq '')
          {
            $DPST
          }
          ElseIf ($PF -eq '')
          {
            $DPST | ? {$_.Region -eq $RF}
          }
          ElseIf ($RF -eq '')
          {
            $DPST | ? {$_.FilePath -like "*$PF*"}
          }
          Else
          {
            $DPST | ? {$_.Region -eq $RF -and $_.FilePath -like "*$PF*"}
          }
    
        # Output the array $result as-is, via an aux. wrapper array.
        , $result
    
    }
    

    Note: You don't strictly need the immediate $result variable; you could use , @(if ...) directly.

    However, note that in neither case will the command's output stream (emit objects as they're being created), because the entire output must be collected first, before the aux. array can be constructed around it.

    0 讨论(0)
提交回复
热议问题