是否有一个简单的实现来测试数组的所有元素是否完全相同?

Is there a simple implementation to test whether all elements of an array are exactly the same?

我需要确定一个数组的所有元素是否完全相同。我希望它也能很好地处理所有数据类型,Object/String/Int/etc。

有没有在 PowerShell 中执行此操作的简单方法?

function Test-ArrayElementsEqual {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory,Position = 0,ValueFromPipeline)]
        [object]
        $Array,
    )

    $test = $null
    foreach ($item in $Array) {
        if(!$test){
            $test = $item
            continue
        }
        if($test -ne $item){
            return $false
        }
    }
    return $true
}

这就是我现在拥有的,但我感觉它是一个错误的实现,而且还有更优雅的东西。

任何帮助都会很棒。

编辑:


自上次发布以来,我为此整理了一个非常好的实用函数。它支持对象、数组、所有数值数据类型、XML 等

代码如下:

https://github.com/visusys/VSYSUtility/blob/main/Public/Test-ObjectContentsAreIdentical.ps1

在我的评论中,对于简单的比较,您可以使用 what 在他的评论中只添加一个类型比较,这可以通过使用 .GetType() 方法来完成。

如果所有元素的类型和值相同,function 将 return $true 并且将 return index 和期望值/类型不同或值不同的第一个元素的类型。

function Test-ArrayElementsEqual {
[CmdletBinding()]
param (
    [Parameter(Mandatory)]
    $InputObject
)
    begin
    {
        $refVal = $InputObject[0]
        $refType = $refVal.GetType()
        $index = 0
    }

    process
    {
        foreach($element in $InputObject)
        {
            if($element -isnot $refType)
            {
                "Different Type at Position $index. Expected Type was {0}." -f $refType.FullName
                return
            }
            if($element -ne $refVal)
            {
                "Different Value at Position $index. Expected Value was $refVal."
                return
            }

            $index++
        }

        $true
    }
}

测试示例

$arr1 = 123, 123, '123'
$arr2 = 123, 345, 123
$arr3 = 'test', 'test', 'test'

结果

PS /> Test-ArrayElementsEqual $arr1
Different Type at Position 2. Expected Type was System.Int32.

PS /> Test-ArrayElementsEqual $arr2
Different Value at Position 1. Expected Value was 123.

PS /> Test-ArrayElementsEqual $arr3
True

如果您正在寻找一种比较不同对象是否相同的方法,您可能会找到有关此问题答案的有用信息:Prevent adding pscustomobject to array if already exists