我尝试从哈希表创建自定义对象以管道导出到Csv。 但是,当我创建csv文件时,属性都是乱序的。 我在下面写了评论以显示订单。
function CreateStatusCustomObject
{
param([Parameter(Mandatory=$true)][Hashtable]$Values)
$statusCustomObject = New-Object -TypeName PSObject
foreach($value in $Values.GetEnumerator())
{
$statusCustomObject | Add-Member -MemberType NoteProperty -Name $value.Name -Value $value.Value
}
return $statusCustomObject
}
$Cec = 'a'
$DnsServer = 'b'
$subnetInfoCidr = 'c'
$oldServerRefreshIntervalValue = 'd'
$anotherProperty = 'e'
$statusCustomObject = CreateStatusCustomObject @{Cec = $Cec; #2
DnsServer = $DnsServer; #5
Cidr = $subnetInfoCidr; #1
OldServerRefreshIntervalValue = $oldServerRefreshIntervalValue;#3
AnotherProperty = $anotherProperty} #4
如何强制订单成为哈希表中的内容?
答案 0 :(得分:2)
您可以使用[ordered]
类型加速器。我认为这是在PowerShell v3中引入的。
在你的情况下,这应该可以解决问题:
$statusCustomObject = CreateStatusCustomObject [ordered]@{Cec = $Cec;
DnsServer = $DnsServer;
Cidr = $subnetInfoCidr;
OldServerRefreshIntervalValue = $oldServerRefreshIntervalValue;
AnotherProperty = $anotherProperty}
在幕后,创建的对象实际上是一个OrderedDictionary。
由于这仍然依赖于PowerShell 3,你也可以直接创建你的对象(并跳过函数......假设我有一个特定的原因,我错过了),这样:
$statusCustomObject = [pscustomobject]@{
Cec = $Cec
DnsServer = $DnsServer
Cidr = $subnetInfoCidr
OldServerRefreshIntervalValue = $oldServerRefreshIntervalValue
AnotherProperty = $anotherProperty
}
结果应该是正确的顺序,但如果没有,你可以组合加速器(例如[pscustomobject][ordered]@{}
)
答案 1 :(得分:0)
我会用下面的模式解决问题。
<强> CODE 强>
#data
$listofitems = @()
$myDataItem = [PSCustomOBject]@{
Cec = 'a'
DnsServer = 'b'
subnetInfoCidr = 'c'
oldServerRefreshIntervalValue = 'd'
anotherProperty = 'e'
}
$listofitems += $myDataItem
$myDataItem = [PSCustomOBject]@{
Cec = 'a1'
DnsServer = 'b1'
subnetInfoCidr = 'c1'
oldServerRefreshIntervalValue = 'd1'
anotherProperty = 'e1'
}
$listofitems += $myDataItem
cls
Write-Output "all properties"
$listofitems | ConvertTo-Csv -NoTypeInformation
Write-Output "`r`nproperties in my own order"
$listofitems | Select oldServerRefreshIntervalValue, DnsServer | ConvertTo-Csv -NoTypeInformation
<强>输出强>
all properties
"Cec","DnsServer","subnetInfoCidr","oldServerRefreshIntervalValue","anotherProperty"
"a","b","c","d","e"
"a1","b1","c1","d1","e1"
properties in my own order
"oldServerRefreshIntervalValue","DnsServer"
"d","b"
"d1","b1"
答案 2 :(得分:0)
你也可以对你的功能进行分类,如下所示:
function CreateStatusCustomObject
{
param([Parameter(Mandatory=$true)][Hashtable]$Values)
$statusCustomObject = New-Object -TypeName PSObject
$Values.Keys | sort -CaseSensitive | %{
$key=$_;$value=$Values[$_];
$statusCustomObject | Add-Member -MemberType NoteProperty -Name $key -Value $value
}
return $statusCustomObject
}