包括if / else逻辑

时间:2014-06-15 11:09:19

标签: powershell outlook

您好我正在尝试if/else并编写两个单独的文件,if PST存在,然后执行以下操作。 Export-Csv -NoTypeInformation C:\$UserName-$ComputerName-OpenPSTs-$Date.csv

Else Export-Csv -NoTypeInformation C:\$UserName-$ComputerName-NOPSTs-$Date.csv

有人可以建议。

$Date = Get-Date -format d-M-yyyy
$UserName = $env:USERNAME
$ComputerName = $env:COMPUTERNAME
$Outlook = New-Object -comObject Outlook.Application

$object = $Outlook.Session.Stores | Where {$_.FilePath -like "*.PST"} | Select `
@{Expression={$_.DisplayName}; Label="PST Name in Outlook"},`
@{Expression={$_.FilePath}; Label="PST Location/FileName"},`
@{Expression={$_.IsOpen}; Label="PST Open in Outlook"},`
@{Expression={(Get-Item $_.FilePath).Length / 1KB}; Label="PST File Size (KB)"}
$object | Add-Member -MemberType NoteProperty -Name 'ComputerName' -Value $ComputerName
$object | Add-Member -MemberType NoteProperty -Name 'UserName' -Value $UserName
$object | Export-Csv -NoTypeInformation C:\$UserName-$ComputerName-OpenPSTs-$Date.csv

Start-Sleep 5
Get-Process | Where {$_.Name -like "Outlook*"} | Stop-Process

1 个答案:

答案 0 :(得分:0)

您可以使用Where-Object循环和嵌套条件替换ForEach-Object过滤器:

$Outlook.Session.Stores | % {
  if ($_.FilePath -like '*.pst') {
    $_ | select ... | Export-Csv 'OpenPST.csv' -NoType -Append
  } else {
    $_ | select ... | Export-Csv 'NoPST.csv' -NoType -Append
  }
}
但是,这可能效果不太好,因为它反复附加到输出文件。使用互补过滤器运行2个管道可能更好:

$stores = $Outlook.Session.Stores

$stores | ? { $_.FilePath -like '*.pst' } | select ... |
    Export-Csv 'OpenPST.csv' -NoType
$stores | ? { $_.FilePath -notlike '*.pst' } | select ... |
    Export-Csv 'NoPST.csv' -NoType