PowerShell: Function doesn't have proper return value
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.
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
.
I have modified the bit of your script, to make it run the way you want it. I'm not exactly sure you would want to compare files only by the .Count property though, but its not within the scope of this question. If that wasn't what you were looking after, please comment and I'll try to edit this answer. Basically from what I understand you wanted to run a condition check after the function, while it can be easily implemented inside the function.
$Dir1 ="C:\Dir1"$Dir2 ="C:\Users\a.pawlak\Desktop\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 Nameif ($fileList1.Count -ne $fileList2.Count){Write-Host "Following files are different:"Compare-Object -ReferenceObject $fileList1 -DifferenceObject $fileList2 -Property FullName -PassThru | Format-Table FullNameWrite-Host "Test FAILED" -BackgroundColor Red}else { return $trueWrite-Output "Test OK" }}Test-Diff $Dir1 $Dir2
If there is anything unclear, let me know
AlexP