Schlagwort-Archive: Powershell

PowerShell Outlook Scripting

This small PowerShell example opens my Outlook and searches for a inbox folder called „Planungen“.
It’s going through all mail and processes them if they have special keywords in them like Planung and KAR. If there are keywords like NB or Nachberechnung it’s not processed. Then it saves the attachment to a temporary Directory and uses pscp to copy it over to a linux machine. It uses my Windows kerberos key to authenticate via GSSAPI so I don’t need a RSA Key or password. It’s executed each day as a scheduled job. Neat, isn’t it?


$pscp_path="C:\Users\someuser\Downloads\pscp.exe"
$linux_path="somehost.de:/tmp"
$linux_user="someuser"
$filepath = "C:\temp\"
$date = get-date -format d
$time = get-date -format h-mm
$log = "C:\Temp\Logs\parameterpflege_" + $date + "_" + $time + ".log"

$olFolderInbox = 6 
$outlook = new-object -com outlook.application; 
$ns = $outlook.GetNameSpace("MAPI");
$inbox = $ns.GetDefaultFolder($olFolderInbox)
$planungsordner=$inbox.Folders | where-object { $_.name -eq "Planungen" }
$messages = $planungsordner.items 

foreach($message in $messages){
  If ($message.subject -match ".*Planung.*" -And $message.subject -match ".*KAR.*" -And $message.UnRead -eq "$true" -And (!($message.subject -match ".*NB.*" -Or $message.subject -match ".*Nachberechnung.*"))) {
    Start-Transcript -Force -Path $log
    $subject=$message.subject
    write-host "bearbeite Mail ""$subject"""
    # save attachment
    $message.attachments|foreach {
      $attachmentname = $_.filename
      If ($attachmentname.Contains("doc")) {
        Write-Host "save $attachmentname to $filepath"
        $_.saveasfile((Join-Path $filepath $attachmentname)) 
      } 
    }
    # mark as read so it's not gonna processed again
    $message.UnRead = $false
    $docfile = "$filepath" + $attachmentname
    Write-Host "kopiere $docfile nach $linux_user@$linux_path"
    &$pscp_path $docfile $linux_user@$linux_path
    Stop-Transcript
  }
}