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:
I tested the path to ensure it's right, as you can see in the for loop above - and the file does exist.
I created the $mail object so that's not null and it sends perfectly - just with no attachment
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.
I figured it out eventually! - it was a combination of two things.
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.