2017-11-20,完全重写了函数以提高性能并添加了-ArrayBase和对PSStandardMembers和分组对象的支持。
Flatten-Object
递归地展平包含数组、哈希表和(自定义)对象的对象。所提供的objects的所有添加属性将与其他对象对齐。
需要PowerShell版本2或更高版本。
Cmdlet
Function Flatten-Object {
[CmdletBinding()]Param (
[Parameter(ValueFromPipeLine = $True)][Object[]]$Objects,
[String]$Separator = ".", [ValidateSet("", 0, 1)]$Base = 1, [Int]$Depth = 5, [Int]$Uncut = 1,
[String[]]$ToString = ([String], [DateTime], [TimeSpan]), [String[]]$Path = @()
)
$PipeLine = $Input | ForEach {$_}; If ($PipeLine) {$Objects = $PipeLine}
If (@(Get-PSCallStack)[1].Command -eq $MyInvocation.MyCommand.Name -or @(Get-PSCallStack)[1].Command -eq "<position>") {
$Object = @($Objects)[0]; $Iterate = New-Object System.Collections.Specialized.OrderedDictionary
If ($ToString | Where {$Object -is $_}) {$Object = $Object.ToString()}
ElseIf ($Depth) {$Depth--
If ($Object.GetEnumerator.OverloadDefinitions -match "[\W]IDictionaryEnumerator[\W]") {
$Iterate = $Object
} ElseIf ($Object.GetEnumerator.OverloadDefinitions -match "[\W]IEnumerator[\W]") {
$Object.GetEnumerator() | ForEach -Begin {$i = $Base} {$Iterate.($i) = $_; $i += 1}
} Else {
$Names = If ($Uncut) {$Uncut--} Else {$Object.PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames}
If (!$Names) {$Names = $Object.PSObject.Properties | Where {$_.IsGettable} | Select -Expand Name}
If ($Names) {$Names | ForEach {$Iterate.$_ = $Object.$_}}
}
}
If (@($Iterate.Keys).Count) {
$Iterate.Keys | ForEach {
Flatten-Object @(,$Iterate.$_) $Separator $Base $Depth $Uncut $ToString ($Path + $_)
}
} Else {$Property.(($Path | Where {$_}) -Join $Separator) = $Object}
} ElseIf ($Objects -ne $Null) {
@($Objects) | ForEach -Begin {$Output = @(); $Names = @()} {
New-Variable -Force -Option AllScope -Name Property -Value (New-Object System.Collections.Specialized.OrderedDictionary)
Flatten-Object @(,$_) $Separator $Base $Depth $Uncut $ToString $Path
$Output += New-Object PSObject -Property $Property
$Names += $Output[-1].PSObject.Properties | Select -Expand Name
}
$Output | Select ([String[]]($Names | Select -Unique))
}
}; Set-Alias Flatten Flatten-Object
语法
<Object[]> Flatten-Object [-Separator <String>] [-Base "" | 0 | 1] [-Depth <Int>] [-Uncut<Int>] [ToString <Type[]>]
或者:
Flatten-Object <Object[]> [[-Separator] <String>] [[-Base] "" | 0 | 1] [[-Depth] <Int>] [[-Uncut] <Int>] [[ToString] <Type[]>]
参数
-Object[] <Object[]>
要展开的对象(或对象)。
-Separator <String>
(默认值:.
)
递归属性名称之间使用的分隔符。
-Depth <Int>
(默认值:5
)
展开递归属性的最大深度。任何负值都将导致无限深度,并可能导致无限循环。
-Uncut <Int>
(默认值:1
)
将保留的对象迭代次数,进一步限制对象属性仅为DefaultDisplayPropertySet
。任何负值都将显示所有对象的所有属性。
-Base "" | 0 | 1
(默认值:1
)
嵌套数组的第一个索引名称:
1
,数组将以1为基准: <Parent>.1
,<Parent>.2
,<Parent>.3
,...
0
,数组将以0为基准: <Parent>.0
,<Parent>.1
,<Parent>.2
,...
""
,数组中的第一项将没有名称,然后以1开始命名: <Parent>
,<Parent>.1
,<Parent>.2
,...
-ToString <Type[]= [String], [DateTime], [TimeSpan]>
一个值类型的列表(默认为[String],[DateTime],[TimeSpan]),将被转换为字符串而不是进一步展开。例如,一个[DateTime]可以展开为额外的属性,如Date,Day,DayOfWeek等,但将被转换为单个(String)属性。
注意:
参数-Path仅供内部使用,但可以用于前缀属性名称。
示例:
回答具体问题:
(Get-Content "PATH_TO\test.json" -Raw | ConvertFrom-Json) | Flatten-Object | Convertto-CSV -NoTypeInformation | Set-Content "PATH_TO\test.csv"
结果:
{
"url": "http://test.test",
"slug": "slug",
"id": 10011,
"link": "http://test.er",
"level": 1,
"areas.2": "area_b",
"areas.1": "area_a",
"disciplines.3": "discipline_c",
"disciplines.2": "discipline_b",
"disciplines.1": "discipline_a",
"subject": "testing",
"title": "Test procedure",
"email": "test@test.com"
}
压力测试一个更复杂的自定义对象:
New-Object PSObject @{
String = [String]"Text"
Char = [Char]65
Byte = [Byte]66
Int = [Int]67
Long = [Long]68
Null = $Null
Booleans = $False, $True
Decimal = [Decimal]69
Single = [Single]70
Double = [Double]71
Array = @("One", "Two", @("Three", "Four"), "Five")
HashTable = @{city="New York"; currency="Dollar"; postalCode=10021; Etc = @("Three", "Four", "Five")}
Object = New-Object PSObject -Property @{Name = "One"; Value = 1; Text = @("First", "1st")}
} | Flatten
结果:
Double : 71
Decimal : 69
Long : 68
Array.1 : One
Array.2 : Two
Array.3.1 : Three
Array.3.2 : Four
Array.4 : Five
Object.Name : One
Object.Value : 1
Object.Text.1 : First
Object.Text.2 : 1st
Int : 67
Byte : 66
HashTable.postalCode : 10021
HashTable.currency : Dollar
HashTable.Etc.1 : Three
HashTable.Etc.2 : Four
HashTable.Etc.3 : Five
HashTable.city : New York
Booleans.1 : False
Booleans.2 : True
String : Text
Char : A
Single : 70
Null :
扁平化分组对象:
$csv | Group Name | Flatten | Format-Table
# https://stackoverflow.com/a/47409634/1701026
扁平化常见对象:
(Get-Process)[0] | Flatten-Object
或者对象列表(数组):
Get-Service | Flatten-Object -Depth 3 | Export-CSV Service.csv
请注意,以下命令需要几个小时来计算:
Get-Process | Flatten-Object | Export-CSV Process.csv
为什么?因为它会生成一个包含几百行和几千列的表格。所以,如果您想要使用此命令进行扁平化处理,最好限制行数(使用Where-Object
cmdlet)或列数(使用Select-Object
cmdlet)。