2015-12-02 26 views
0

我想提出條件,我的這部分代碼:PSObject,物業與條件

$objInfos = New-Object PSObject -Property @{ 
        Dossier = [string]"$($logs[0])" 
        "Taille totale" = [double]$logs[1] 
        "Categorie recherchee" = [double]$logs[2] 
        "Pourcentage" = [double]$logs[3] 
        "Date de dernier acces" = [DateTime]"$($logs[5])" 
} 

我需要每一個案件有狀況,這樣的:

$objInfos = New-Object PSObject -Property @{ 
        if ($test -eq 1){ 
         Dossier = [string]"$($logs[0])" 
        } 
        "Taille totale" = [double]$logs[1] 
        "Categorie recherchee" = [double]$logs[2] 
        "Pourcentage" = [double]$logs[3] 
        "Date de dernier acces" = [DateTime]"$($logs[5])" 
} 

我試着這種方式並沒有工作

鍵入哈希文字後缺少'='運算符。

有人知道該怎麼做嗎?

+1

你可以用'添加-Member'添加該物業如果需要。我看到你最近在這裏問了一些問題,但還沒有接受任何答案,儘管已經有一些好的答案。請這樣做,或者對作者發表評論,以便他們可以根據需要進行修改。 – arco444

回答

3

您可以在單獨的語句中創建Hashtable,用值填充它,然後將其傳遞給New-Object cmdlet。

$Hashtable = @{} 
if ($test -eq 1){ 
    $Hashtable.Add('Dossier', [string]"$($logs[0])") 
} 
$Hashtable.Add("Taille totale", [double]$logs[1]) 
$Hashtable.Add("Categorie recherchee", [double]$logs[2]) 
$Hashtable.Add("Pourcentage", [double]$logs[3]) 
$Hashtable.Add("Date de dernier acces", [DateTime]"$($logs[5])") 
$objInfos = New-Object PSObject -Property $Hashtable 

如果你想在同一順序屬性添加到Hashtable元素,那麼你就需要使用OrderedDictionary而不是Hashtable

$Hashtable = New-Object System.Collections.Specialized.OrderedDictionary 
+0

它完美地工作,謝謝! – Kikopu

+0

現在我有一個新的問題,在這裏的條件之前,我用這個: '$ tab |選擇Dossier,「Taille Totale」,「Categorie recherchee」,「Pourcentage」,「Date de dernier acces」| Sort-Object「Pourcentage」 - 下降| format-table -autosize | out-string -width 4000 | out-file -append O:\ ****** \ ****** \ parcoursArborescence \ bilanAnalyse.txt'我怎麼能讓他只寫正確的? – Kikopu

+0

@Kikopu從管道中刪除'select'命令有幫助嗎? – PetSerAl

1

您可以conditonally條目添加到屬性哈希表@PetSerAl建議:

$props = @{ 
    'Taille totale'   = [double]$logs[1] 
    'Categorie recherchee' = [double]$logs[2] 
    'Pourcentage'   = [double]$logs[3] 
    'Date de dernier acces' = [DateTime]$logs[5] 
} 

if ($test -eq 1) { 
    $props['Dossier'] = "$($logs[0])" 
} 

$objInfos = New-Object PSObject -Property $props 

您可以使用Add-Member爲@ arco444建議在評論你的問題:

$objInfos = New-Object PSObject -Property @{ 
    'Taille totale'   = [double]$logs[1] 
    'Categorie recherchee' = [double]$logs[2] 
    'Pourcentage'   = [double]$logs[3] 
    'Date de dernier acces' = [DateTime]$logs[5] 
} 

if ($test -eq 1) { 
    $objInfos | Add-Member -Type NoteProperty -Name 'Dossier' -Value "$($logs[0])" 
} 

或者,您可以添加屬性不論,但設置爲根據您的檢查結果它的價值:

$objInfos = New-Object PSObject -Property @{ 
    'Dossier'    = if ($test -eq 1) {"$($logs[0])"} else {''} 
    'Taille totale'   = [double]$logs[1] 
    'Categorie recherchee' = [double]$logs[2] 
    'Pourcentage'   = [double]$logs[3] 
    'Date de dernier acces' = [DateTime]$logs[5] 
}