You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对PowerShell中的多维ArrayList按指定元素排序?

解决PowerShell多维ArrayList按指定维度排序的问题

方法1:使用ArrayList的Sort方法结合自定义比较器

你可以通过创建自定义比较器,告诉Sort()方法按照子数组的第2个元素(索引1)进行排序。示例代码如下:

# 定义比较器:比较两个子数组的索引1元素
$comparer = [System.Collections.Comparer]::Create({
    param($a, $b)
    # 按字符串比较,若需数值比较可转成[int]或其他类型
    [string]::Compare($a[1], $b[1])
})

# 对ArrayList执行排序
$Installs.Sort($comparer)

如果需要降序排序,只需将比较结果取反:

$comparer = [System.Collections.Comparer]::Create({
    param($a, $b)
    -[string]::Compare($a[1], $b[1])
})
$Installs.Sort($comparer)

方法2:转换为自定义对象后用Sort-Object排序(更直观)

这种方法可读性更强,符合PowerShell使用习惯:先将每个子数组转换为带命名属性的对象,再用Sort-Object按指定属性排序:

# 将ArrayList中的子数组转换为自定义对象并排序
$sortedInstalls = $Installs | ForEach-Object {
    [PSCustomObject]@{
        RebootRequired = $_[0]
        SoftPaqName = $_[1]
        SilentCommand = $_[2]
    }
} | Sort-Object -Property SoftPaqName

# 若需转回原数组结构,可执行以下操作
$Installs.Clear()
$sortedInstalls | ForEach-Object {
    $Installs.Add(@($_.RebootRequired, $_.SoftPaqName, $_.SilentCommand)) | Out-Null
}

额外优化建议

你可以简化原代码的数组生成逻辑,直接生成排序后的结果,无需先创建ArrayList:

# 直接生成按索引1排序后的数组
$Installs = Get-ChildItem -Path $HPImagingAssistantSoftPaqPath -Filter *.cva | ForEach-Object {
    $CVAFileContents = Get-Content $_.FullName -Raw
    if ($CVAFileContents -match '(?s).*?\[General\].*?SystemMustBeRebooted=(\d).*?\[Install Execution\].*?SilentInstall=(.*?)\n.*') {
        $s = $_.FullName.Split("\")[-1].Split(".")[0]
        @($Matches[1], $s, $Matches[2])
    }
} | Sort-Object -Property { $_[1] }

# 若仍需ArrayList类型,执行转换
$InstallsArrayList = [System.Collections.ArrayList]$Installs

内容的提问来源于stack exchange,提问作者user66001

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 17:38:21