Mat*_*a72 6 powershell function compareobject
我写了一个powershell脚本来比较两个文件夹的内容:
$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
}
Run Code Online (Sandbox Code Playgroud)
如果我设置了一个断点Compare-Object,并且我在控制台中运行此命令,我会得到差异列表.如果我运行整个脚本,我没有得到任何输出.为什么?
我在PowerGUI脚本编辑器中工作,但我也尝试了普通的ps控制台.
编辑:
问题是检查脚本的结尾.
$i = Test-Diff $Dir1 $Dir2
if($i) {
Write-Output "Test OK"
...
Run Code Online (Sandbox Code Playgroud)
如果我Test-Diff不通过$i =支票打电话,它就可以了!
Test-Diff 返回一个对象数组而不是预期的bool值:
[DBG]: PS D:\>> $i | ForEach-Object { $_.GetType() } | Format-Table -Property Name
Name
----
FormatStartData
GroupStartData
FormatEntryData
GroupEndData
FormatEndData
Boolean
Run Code Online (Sandbox Code Playgroud)
如果我注释掉该行Compare-Object,则返回值是一个布尔值,如预期的那样.
问题是:为什么?
我在这里找到了答案:http://martinzugec.blogspot.hu/2008/08/returning-values-from-fuctions-in.html
这样的功能:
Function bar {
[System.Collections.ArrayList]$MyVariable = @()
$MyVariable.Add("a")
$MyVariable.Add("b")
Return $MyVariable
}
Run Code Online (Sandbox Code Playgroud)
使用PowerShell返回对象的方式:@(0,1,"a","b")而不是@("a","b")
要使此功能按预期工作,您需要将输出重定向到null:
Function bar {
[System.Collections.ArrayList]$MyVariable = @()
$MyVariable.Add("a") | Out-Null
$MyVariable.Add("b") | Out-Null
Return $MyVariable
}
Run Code Online (Sandbox Code Playgroud)
在我们的例子中,函数必须按照Koliat的建议进行重构.
| 归档时间: |
|
| 查看次数: |
12129 次 |
| 最近记录: |