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"
修改
这是不相同
推荐答案
您可以比较两个 PSObject
对象是否属性相等es和值使用 Compare-Object
来比较 PSObject的
的对象。示例:属性
属性
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屋!
查看全文