2017-03-02 90 views
0

我使用PowerShell刮取網頁並從頁面上的表格元素構建對象。有時每個表格元素都是唯一的,有時候會有多個具有相同名稱的元素。構建自定義對象時避免屬性名稱衝突

如果我打了一個屬性的第二個實例刮期間,我想通過數字來命名新的屬性(即連續序列,如果我再打名)。

我設法讓每個下面的代碼這方面的工作,但有一個更好的方式來做到這一點?

$PropertyExists = $Object.PSObject.Properties.Name | 
    Where { $_ -like "$PropertyName*" } | Sort -Descending | Select -First 1 

If ($PropertyExists) { 
    $PropertyNumber = [int]($PropertyExists -split "(\d+$)")[1] + 1 
} Else { 
    $PropertyNumber = "" 
} 

$Object | Add-Member –MemberType NoteProperty 
    –Name "$PropertyName$PropertyNumber" 
    –Value $PropertyValue 

回答

1

財產轉換爲動態數組,如果它已經定義:

$prop = $Object.$PropertyName 
if ($prop -is [Collections.ArrayList]) { 
    $prop.Add($PropertyValue) >$null 
} elseif ($prop -is [object]) { 
    $Object.$PropertyName = [Collections.ArrayList]@($prop, $PropertyValue) 
} else { 
    Add-Member @{$PropertyName = $PropertyValue} -InputObject $Object 
} 

這樣,你就可以統一處理單值和多值屬性:

$Object.foo | ForEach { .... } 

另一個優點是我們不太經常調用緩慢的Add-Member。

+0

偉大的解決方案,謝謝!唯一的小問題是你的代碼假設這些屬性總是有內容(並且在我的場景中它們有時是空的),但是我通過將'elseif($ prop)'改爲'ElseIf($ Prop -is [object])來解決這個問題' 。 –

+0

很好,趕快,謝謝。 – wOxxOm