Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell: Function doesn't have proper return value

I wrote a powershell script to compare the content of two folders:

$Dir1 ="d:\TEMP\Dir1"
$Dir2 ="d:\TEMP\Dir2"

function Test-Diff($Dir1, $Dir2) {
    $fileList1 = Get-ChildItem $Dir1 -Recurse | Where-Object {!$_.PsIsContainer} | Get-Item | Sort-Object -Property Name
    $fileList2 = Get-ChildItem $Dir2 -Recurse | Where-Object {!$_.PsIsContainer} | Get-Item | Sort-Object -Property Name

    if($fileList1.Count -ne $fileList2.Count) {
        Write-Host "Following files are different:"
        Compare-Object -ReferenceObject $fileList1 -DifferenceObject $fileList2 -Property Name -PassThru | Format-Table FullName
        return $false
    }

    return $true
}

$i = Test-Diff $Dir1 $Dir2

if($i) { 
    Write-Output "Test OK" 
} else { 
    Write-Host "Test FAILED" -BackgroundColor Red
}

If I set a break point on Compare-Object, and I run this command in console, I get the list of differences. If I run the whole script, I don't get any output. Why?

I'm working in PowerGUI Script Editor, but I tried the normal ps console too.

EDIT:

The problem is the check on the end of the script.

$i = Test-Diff $Dir1 $Dir2

if($i) { 
   Write-Output "Test OK" 
...

If I call Test-Diff without $i = check, it works!

Test-Diff returns with an array of objects and not with an expected bool value:

[DBG]: PS D:\>> $i | ForEach-Object { $_.GetType() } | Format-Table -Property Name
 Name                                                                                                                        
 ----                                                                                                                        
 FormatStartData                                                                                                             
 GroupStartData                                                                                                              
 FormatEntryData                                                                                                             
 GroupEndData                                                                                                                
 FormatEndData                                                                                                               
 Boolean         

If I comment out the line with Compare-Object, the return value is a boolean value, as expected.

The question is: why?

like image 930
Mattia72 Avatar asked Mar 26 '14 14:03

Mattia72


People also ask

How do you return a value from a function in PowerShell?

If you are inside of a function and return a value with the return keyword, the function will return that value and exit the function. The return keyword causes the function to exit after outputting the first process. PowerShell will then generate output for both processes.

How do I get the return value of a PowerShell script?

The return keyword exits a function, script, or script block. It can be used to exit a scope at a specific point, to return a value, or to indicate that the end of the scope has been reached.

Why we use $_ in PowerShell?

$_ is a variable created by the system usually inside block expressions that are referenced by cmdlets that are used with pipe such as Where-Object and ForEach-Object . But it can be used also in other types of expressions, for example with Select-Object combined with expression properties.

How does $_ work in PowerShell?

The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.


2 Answers

I've found the answer here: http://martinzugec.blogspot.hu/2008/08/returning-values-from-fuctions-in.html

Functions like this:

Function bar {
 [System.Collections.ArrayList]$MyVariable = @()
 $MyVariable.Add("a")
 $MyVariable.Add("b")
 Return $MyVariable
}

uses a PowerShell way of returning objects: @(0,1,"a","b") and not @("a","b")

To make this function work as expected, you will need to redirect output to null:

Function bar {
 [System.Collections.ArrayList]$MyVariable = @()
 $MyVariable.Add("a") | Out-Null
 $MyVariable.Add("b") | Out-Null
 Return $MyVariable
}

In our case, the function has to be refactored as suggested by Koliat.

like image 52
Mattia72 Avatar answered Oct 25 '22 01:10

Mattia72


An alternative to adding Out-Null after every command but the last is doing this:

$i = (Test-Diff $Dir1 $Dir2 | select -last 1)

PowerShell functions always return the result of all the commands executed in the function as an Object[] (unless you pipe the command to Out-Null or store the result in a variable), but the expression following the return statement is always the last one, and can be extracted with select -last 1.

like image 33
Raphael Avatar answered Oct 25 '22 00:10

Raphael