如何对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
相关产品推荐
相关产品推荐

