Using the same variable as parameter and storage when calling a function in powershell

Recently I had this problem. After investigating a lot of hours, finally I discovered that the problem was in using the same variable for:

  • Storing the value returned by the function
  • Pass it as a parameter to the function

So taken into account below function:

Function Create-Filter($filter)
    $filter.Split(',') | ForEach-Object {"*.$($_.Trim())"}

(Above function gets a string variable such as "csproj, vbproj" and converts it into *.csproj *.vbproj)

...below code is not working, variable $filter used for -Include parameter does not like to Get-ChildItem and it is returning nothing:

$filter = "csproj, vbproj"
$filter = Create-Filter ($filter)
Get-ChildItem "D:\Path\To\My\Root\Folder" -Include $filter -Recurse

Instead below one is working by using a different variable for storing and pass it as a parameter:

$filter = "csproj, vbproj"  
$formattedfilter = Create-Filter ($filter)
Get-ChildItem "D:\Path\To\My\Root\Folder" -Include $formattedfilter -Recurse

... now Get-ChildItem works.

In other languages one can use the same variable for passing it as a parameter and storing the value returned by the function. So could you explain me why in powershell this does not work if one uses the same variable?

1 answer

  • answered 2019-06-17 18:59 mhu

    Not sure why your code won't work, as the return in your case is redundant and the result is put on the output stream.

    So the same code but refactored:

    function New-Filter
        param (
            [String[]] $filter
        return $filter.Split(',') | ForEach-Object {"*.$($_.Trim())"}
    $filter = @("csproj, vbproj")
    $filter = New-Filter $filter
    Get-ChildItem -Path "D:\Path\To\My\Root\Folder" -Include $filter -Recurse