Comobject outlook.application for Autmoation

Welcome Forums General PowerShell Q&A Comobject outlook.application for Autmoation

This topic contains 7 replies, has 3 voices, and was last updated by

 
Participant
3 years, 10 months ago.

  • Author
    Posts
  • #20913

    Participant
    Points: 0
    Rank: Member

    I am using the script below, instead off attachments I would like the .msg file its self saved to a directory

    #file path
    $filepath = “c:\test\”
    
    
    #set outlook to open
    $o = New-Object -comobject outlook.application
    $n = $o.GetNamespace(“MAPI”)
    
    
    #you'll get a popup in outlook at this point where you pick the folder you want to scan
    $f = $n.pickfolder()
    
    #date string to search for in attachment name
    $date = Get-Date -Format yyyyMMdd
    
    
    #now loop through them and grab the attachments
    $f.Items | foreach {
        $_.attachments | foreach {
        Write-Host $_.filename
        $a = $_.filename
        If ($a.Contains($date)) {
        $_.saveasfile((Join-Path $filepath $a))
          }
      }
    }
    

    thank you

  • #20915

    Participant
    Points: 0
    Rank: Member

    Hey fella,

    Try something like this :

    #file path
    $filepath = 'c:\temp\'
     
     
    #set outlook to open
    $objOutlook = New-Object -ComObject outlook.application
    $namespace = $objOutlook.GetNamespace('MAPI')
     
     
    #you'll get a popup in outlook at this point where you pick the folder you want to scan
    $folder = $namespace.pickfolder()
     
    #date string to search for in attachment name
    $date = Get-Date 
     
     
    #now loop through them and grab the attachments
    $folder.Items | ForEach-Object -Process {
      $modificationDate = $psItem.LastModificationTime  
      If (($modificationDate.day -eq $date.day )-and ($modificationDate.month -eq $date.month )-and ($modificationDate.year -eq $date.year)) 
      {
        $message = $psitem
        $subject = $message.Subject
        $message.SaveAs("C:\temp\$subject.msg")
      }
    }
    
    
    $objOutlook.Quit()
    
  • #20929

    Participant
    Points: 0
    Rank: Member

    Amazing Tim!! thank you again. Works great, I am getting "SaveAs" with "1" argument(s): "The operation failed."

    I thinks its due to multiple emails with the same subject line creating the same name.

    Rember this .... you helped me with. To copy multiple files with the same name

    foreach ($file in  $Source) 
    { $path = $file.FullName 
      $oldname = $file.name.Remove(10,9)
      $extension = $file.extension
      $newFilename = $oldname
      $fileAlreadyExists = Test-Path $newFileName
      $index = 0
      $basename = $NewFileName.Substring(0,$newFilename.Length-4)
      While ($fileAlreadyExists) 
      {
        $index += 1
        $newFileName = "$($basename)_copy$($index)$($Extension)"
        $fileAlreadyExists = Test-Path $newFileName
      }
     Rename-Item -Path $path  -NewName $newFileName -Force
    }
    
    

    can we incorporate this to avoid the save as error? and Make it only pull the last 24 hours worth of messages

    thanks again for all your help!!

  • #20969

    Participant
    Points: 0
    Rank: Member

    Hey Tim getting this error

    The operation failed.
    At line:11 char:5
    + $message.SaveAs("C:\testing\$subject.msg")
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : OperationStopped: (:) [], COMException
    + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException

    You cannot call a method on a null-valued expression.
    At line:16 char:1
    + $objOutlook.Quit()
    + ~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

  • #20977

    Participant
    Points: 0
    Rank: Member

    Ah, might be the way i wrote it out. Can you try it like this instead:

    $message.SaveAs("C:\testing\$($subject).msg")
    
  • #20978

    Participant
    Points: 0
    Rank: Member

    i just tried it its not pulling all the emails and some of them are missng the .msg file extension

  • #20982

    Participant
    Points: 0
    Rank: Member

    OK, I modified the code again. Using a backtick to tell PowerShell that the backslashes should be treated as regular characters.

    Bear in mind if you have any files with ':' or other non approved filename characters, you will get errors for those ones.

    $filename = "C:`\temp`\$($subject).msg"
    $message.SaveAs($filename)
    
  • #20998

    Participant
    Points: 0
    Rank: Member

    check this out

    #file path
    $filepath = 'c:\Msgs\'
     
     
    #set outlook to open
    $objOutlook = New-Object -ComObject outlook.application
    $namespace = $objOutlook.GetNamespace('MAPI')
     
     
    #you'll get a popup in outlook at this point where you pick the folder you want to scan
    $folder = $namespace.pickfolder()
     
    #date string to search for in attachment name
    $date = Get-Date 
     check this out 
     
    #now loop through them and grab the attachments
    $folder.Items | ForEach-Object -Process {
    
    Function Remove-InvalidFileNameChars {
    
        param(
            [Parameter(Mandatory=$true, Position=0)]
            [String]$Name
        )
    
        return [RegEx]::Replace($Name, "[{0}]" -f ([RegEx]::Escape([String][System.IO.Path]::GetInvalidFileNameChars())), '-')
    }
    
    
    $DestinationPath = "C:\Msgs\"
    
    #Get email's subject and date
    [string]$subject = $message.Subject
    [string]$sentOn = $message.SentOn
    
    #Strip subject and date of illegal characters, add .msg extension, and combine
    $fileName = Remove-InvalidFileNameChars -Name ($sentOn + "-" + $subject + ".msg")
    
    #Combine destination path with stripped file name
    $dest = $DestinationPath + $fileName
    
    
    $modificationDate = $psItem.LastModificationTime  
      If (($modificationDate.day -eq $date.day )-and ($modificationDate.month -eq $date.month )-and ($modificationDate.year -eq $date.year)) 
      {
        $message = $psitem
        $subject = $message.Subject
        $message.SaveAs($dest)
      }
    }
     
     
    $objOutlook.Quit()
    

    and then I am going to use the Renaming piece you gave me!! your are Awesome

    
    $sourceDir = 'C:\Msgs'
    Set-Location -Path $sourceDir 
    $Source = Get-ChildItem -Path $sourceDir | Where-Object -FilterScript {
      $_.Extension -match '.msg'
    }
    foreach ($file in  $Source) 
    { $path = $file.FullName 
      $oldname = $file.name.Remove(10,9)
      $extension = $file.extension
      $newFilename = $oldname
      $fileAlreadyExists = Test-Path $newFileName
      $index = 0
      $basename = $NewFileName.Substring(0,$newFilename.Length-4)
      While ($fileAlreadyExists) 
      {
        $index += 1
        $newFileName = "$($basename)_copy$($index)$($Extension)"
        $fileAlreadyExists = Test-Path $newFileName
      }
     Rename-Item -Path $path  -NewName $newFileName -Force
    }
    
    

    Thank you Tim –Solved!

The topic ‘Comobject outlook.application for Autmoation’ is closed to new replies.