gpt4 book ai didi

powershell - Powershell psobject getenumerator一

转载 作者:行者123 更新时间:2023-12-02 23:28:57 25 4
gpt4 key购买 nike

我借用了一些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技能来说有点高级。关于如何防止对象中一项发生错误的任何建议?

最佳答案

好像$comp是一项时,它不是数组。您需要将$comp初始化为一个空数组。我在您的代码中看不到它的来源,但是这样的事情应该起作用:

#This creates an empty array
$comp = @()
$comp += $foo

关于powershell - Powershell psobject getenumerator一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21939026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com