arrays - I keep getting the error "the specified string is not in the form required for an email address" when using Send-MailMessage -
#get max password age policy $maxpwdage=(get-addefaultdomainpasswordpolicy).maxpasswordage.days #expiring in 7 days $7days=(get-date).adddays(7-$maxpwdage).toshortdatestring() $emaillist = get-aduser -filter {enabled -eq $true -and passwordneverexpires -eq $false -and passwordlastset -gt 0} –properties * | {($_.passwordlastset).toshortdatestring() -le $7days} | select-object emailaddress $emailfrom = "code.example@email.com" $emailcc = "code.example2@email.com" $emailsubject = "example subject" $emailbody = "example body" $smtpserver = "192.168.8.130" foreach ($element in $emaillist) { $output = out-string -inputobject $element ; if ($finaloutput=$output.contains(".")) { send-mailmessage -smtpserver $smtpserver -from $emailfrom -to $output -cc $emailcc -subject $emailsubject -body $emailbody -bodyashtml; } } the first several lines run fine, however, when foreach starts errors out , says
the specified string not in form required email address.
i unsure why error, because have converted $element string using out-string.
$element not email address, object happens have property called emailaddress.
out-string results in multi-line string console output of $element| format-table.
don't use out-string, refer emailaddress property directly:
$output = $element.emailaddress or, use -as cast address mailaddress object. if type check fails inside if() statement, send-mailmessage isn't executed.
if(($to = $element.emailaddress -as [mailaddress])) { send-mailmessage -to $to } to avoid send-mailmessage line getting long, use splatting table:
$mailparams = @{ "from" = "code.example@email.com" "cc" = "code.example2@email.com" "subject" = "raw intelligence!" "body" = "howdy! here datez n stuff" "smtpserver" = "192.168.8.130" } and inside loop:
send-mailmessage -to $to @mailparams
Comments
Post a Comment