【发布时间】:2014-02-27 20:19:33
【问题描述】:
我借用了一些 PowerShell 代码来比较哈希表,它返回一个自定义对象,其中包含哈希条目的名称和差异指示。我想输出返回的差异。
对象:
function result( [string]$side ) {
if ($ReturnVals) {
New-Object PSObject -Property @{
'InputKey'= "$path$key";
'SideIndicator' = $side;
'ReferenceValue' = $refValue;
'DifferenceValue' = $difValue;
}
}
else {
New-Object PSObject -Property @{
'InputKey'= "$path$key";
'SideIndicator' = $side;
}
}
}
在处理返回的对象时,如果它为 Null 或有多个条目,一切都很好,GetEnumerator 会执行所需的操作并将输出排序到文件中:
if ($comp -eq $Null) {
write-host $d "No Differences"
out-file -filepath $of -inputobject "`nNo Differences" -Encoding UTF8 -append
}
else {
write-host $d "Differences"
$comp.GetEnumerator() | Sort-Object -property InputKey |
out-file -filepath $of -append -Encoding UTF8
}
如果存在差异,PowerShell 会抛出错误,因为对象没有 GetEnumerator 方法:
方法调用失败,因为 [System.Management.Automation.PSCustomObject] 不包含名为“GetEnumerator”的方法。
我尝试使用 .count 来查看是否有一个差异,但我没有得到一个计数。我得到了 2 个或更多的计数。
自定义对象对于我的 PowerShell 技能来说有点高级。有关如何防止对象中的一项错误的任何建议?
【问题讨论】:
标签: powershell