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

PowerShell中如何按数值而非字符串排序数字数组?

PowerShell字符串数字集合转数值排序解决方法

问题核心是Split(',')拆分后得到的是字符串数组,Sort-Object默认按字符串的ASCII值排序,而非数值大小,因此会出现3128排在53前面的情况。

解决方法有两种:

方法一:排序时强制转换为数值类型

在Sort-Object中通过脚本块,将每个元素转换为整数后再排序:

[string]$PortException = "3128,53,3389,5985,5986"
$PortExceptionArray = $PortException.Split(',') | Sort-Object { [int]$_ }

方法二:先转换为整数数组再排序

先把拆分后的字符串批量转为整数类型,再执行排序:

[string]$PortException = "3128,53,3389,5985,5986"
$PortExceptionArray = [int[]]$PortException.Split(',') | Sort-Object

两种方法最终都会得到按数值从小到大排序的结果:

53
3128
3389
5985
5986

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 05:25:44