2017-05-28 28 views
1

我正在嘗試創建一個函數來記錄word文檔中的一些設置,並使文檔中的信息易於閱讀我需要保留該文檔中屬性的順序原始對象。不幸的是,這意味着我無法'格式正確'。當你無法正確格式化時保留順序

$o = [PSCustomObject]@{ 
    number = 1 
    fruit = 'Orange' 
    Clothing = 'Shirt' 
    Colour = 'blue' 
} 

$p = $o | get-member -type NoteProperty | Select-Object -ExpandProperty Name 

foreach ($n in $p) { 
    Write-Output "$n $($o.$n)" #this line is actually function to write a line into the word doc taking $n and $($o.$n) as parameters 
} 

有問題的部分代碼是'$ o | get-member -type NoteProperty'作爲Powershell在此時對列表重新排序。我不確定我的方法是否正確。

該函數實際上是一個遞歸函數,用於遍歷對象樹並輸出結果。任何關於新方法的想法或糾正我原來的方法都將非常受歡迎。

回答

1

試試這樣說:

$p = $o.psobject.Properties | select -ExpandProperty Name 
+0

作品a魅力,感謝@ mjolinor! –

0

我不明白你的

格式正確

但因爲PowerShell中3,您可以創建有序哈希表的意思:

[ordered]@{ 
    number = 1 
    fruit = 'Orange' 
    Clothing = 'Shirt' 
    Colour = 'blue' 
} 
+0

格式正確,意味着在最後可能的時刻在PowerShell中應用格式化/排序。 我不能使用有序散列表,因爲原始對象將包含嵌套對象,並且不能使用+ =將對象添加到數組。 (如果您認爲這會有幫助,可以發佈此代碼片段) 如果我採用數組方法,則需要將所有下游對象轉換爲有序數組,並通過它們進行遞歸。這可能是可行的,但會使代碼變得複雜。 –