0

so I have this code:

Start-Process Outlook
$o = New-Object -ComObject Outlook.Application
$mail = $o.CreateItem(0)
$mail.To = $recipients
$mail.Subject = "Test"
$mail.Body = $msg

email sends fine, works great, but I want to add a couple attachments based on the message, so I have a loop before I send:

for ($i=1;$i -lt $arr.Count - 1; $i++){
    if ($arr[$i] -eq "Something"){
        $attach="C:\testfile.txt" 
        test-path $attach                            #<- for testing/debug
        write-host $attach                           #<- for testing/debug
        write-host "now will attempt attachment"     #<- for testing/debug
        $mail.Attachment.Add($attach)
    }   
    if ($arr[$i] -eq .... 
}
$mail.Send()

I have a few more identical if statements in the loop as well, but it throws this error on any of them. I get this error:

You cannot call a method on a null-valued expression.
At C:\test.ps1:99 char:17
+                 $mail.Attachment.Add($attach)
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

For debugging I have done:

  1. I tested the path to ensure it's right, as you can see in the for loop above - and the file does exist.

  2. I created the $mail object so that's not null and it sends perfectly - just with no attachment

  3. if I do this in power shell on the cmd line and not in a script it works with the exact same code! e.x if I manually type in $attach="C:\testfile.txt" and then $mail.Attachment.Add($attach) it works.

meh93
  • 311
  • 4
  • 13
  • `$mail.Attachment.Add($attach)` -> `$mail.Attachments.Add($attach)`? – G42 Jan 18 '18 at 15:39
  • Unfortunately, it didn't seem to work... But thanks for that catch! Because two attachments are be added, perhaps its my string[] format. Although I set $attach to a string[] type which is what Attachments needs. – meh93 Jan 18 '18 at 15:49
  • Its not the best dupe but it was the core of the error which is why I flagged it. Glad you got it sorted out. – Matt Jan 18 '18 at 16:38

1 Answers1

0

I figured it out eventually! - it was a combination of two things.

  1. My $attach variable ended up turning into a string, not a string[] and
  2. I was also writing Attachment, not Attachments - thanks gms0ulman for that catch.

It's weird that it seemed to accept Attachment (with no s), and then just called a null-value on what I thought was my input despite it having a value. But I don't think that function exists...weird.

meh93
  • 311
  • 4
  • 13
  • _It's weird that it seemed to accept Attachment_ This is default PowerShell behavior. see https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/set-strictmode?view=powershell-5.1 – Matt Jan 18 '18 at 16:36