本文共 870 字,大约阅读时间需要 2 分钟。
如何将列表转换为自定义对象:PowerShell优化实践
在PowerShell脚本编写中,将字符串列表转换为自定义对象是一个常见的需求。以下是通过多次优化得到的高效实现方案。
$pp = $null$pp = [ordered]@{"Count"=$null;"Gift"=$null}$obj = New-Object -TypeName psobject -property $pp$result = @()$list.Split("`n") | ForEach-Object { $temp = $obj | select * $temp.Count = $_.Split("")[0] $temp.Gift = $_.Substring($_.Split("")[0].Length) $result += $temp}$result $result2 = @()$list -split "`n" | ForEach-Object { $split = $_ -split " ", 2 $temp = [pscustomobject]@{ Count = $split[0] Item = $split[1].trim() } $result2 += $temp}$result2 $gifts = $list -split "`n" | ForEach-Object { $split = $_ -split " ", 2 [pscustomobject]@{ Count = $split[0] Item = $split[1].trim() }}$gifts 转载地址:http://dlxfk.baihongyu.com/