1

我想在这部分代码中添加条件:

$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])"
}

我尝试过这种方式,但没有奏效

散列文字中的键后缺少“=”运算符。

请问有人知道该怎么做吗?

4

2 回答 2

6

您可以Hashtable在单独的语句中创建,用值填充它,然后将其传递给New-Objectcmdlet。

$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
于 2015-12-02T10:10:24.073 回答
2

您可以按照@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]
}
于 2015-12-02T10:45:42.457 回答