PowerShell - 如何判断两个对象是否相同 [英] PowerShell - How to tell if two objects are identical
本文介绍了PowerShell - 如何判断两个对象是否相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设您有两个相同的对象(意味着它们分别具有相同的属性和相同的值).
Let's say you have two objects that are identical (meaning they have the same properties and the same values respectively).
你如何测试相等性?
示例
$obj1
&$obj2
相同
这是我尝试过的:
if($obj1 -eq $obj2)
{
echo 'true'
} else {
echo 'false'
}
# RETURNS "false"
if(Compare-Object -ReferenceObject $obj1 -DifferenceObject $obj2)
{
echo 'true'
} else {
echo 'false'
}
# RETURNS "false"
编辑
这不相同
推荐答案
你可以通过Compare-Object
比较两个PSObject
对象的属性和值是否相等PSObject
对象的 Properties
属性.示例:
You can compare two PSObject
objects for equality of properties and values by using Compare-Object
to compare the Properties
properties of both PSObject
objects. Example:
if ( -not (Compare-Object $obj1.PSObject.Properties $obj2.PSObject.Properties) ) {
"object properties and values match"
}
else {
"object properties and values do not match"
}
如果你想在函数中使用它:
If you want it in a function:
function Test-PSCustomObjectEquality {
param(
[Parameter(Mandatory = $true)]
[PSCustomObject] $firstObject,
[Parameter(Mandatory = $true)]
[PSCustomObject] $secondObject
)
-not (Compare-Object $firstObject.PSObject.Properties $secondObject.PSObject.Properties)
}
这篇关于PowerShell - 如何判断两个对象是否相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文