I have a script file that when ran from within ISE or from the powershell window it works fine. But when ran trough the task scheduler with "runas" the same account it only outputs half the data.
After some troubleshooting i have concluded that the part of the code that is not working is:
Get-ADOrganizationalUnit -SearchBase $OU -Filter {objectclass -eq "organizationalunit"} -SearchScope onelevel -Properties description |
% {
$mailbox = @( get-user -OrganizationalUnit $_.distinguishedName -resultsize unlimited |
? { $_.title -ne "xxx" -and $_.RecipientType -eq "usermailbox" -and $_.RecipientTypeDetails -ne "RoomMailbox" } )
if ($mailbox.count -gt 0) {
$name = $_.name
$mail_customer = $body
$mail_customer += "<h3>" + $name + "</h3>"
$mail_customer += $mailbox | get-MailboxStatistics |
select displayname, lastlogontime, @{ label = "Mailbox Size(MB)"; expression = {
if ($_.totalitemsize.value.toMB() -gt 25600) { "!!!" + $_.TotalItemSize.Value.ToMB() }
else { $_.TotalItemSize.Value.ToMB() }
} } | Sort-Object displayname | ConvertTo-Html -Fragment | Out-String
$count += $mailbox.count
$stattable += @{$name = $mailbox.count}
$mail_customer = $mail_customer | ForEach-Object { $_ -replace '!!!', '<font color="#FF0000">' }
if ( $_.description -ne $null ) {
$mailaddresses = $_.description.split(",")
Send-MailMessage `
-SmtpServer $SMTPserver `
-Encoding $encoding `
-From "$company <noreply@$companylower.se>" `
-To $mailaddresses `
-Subject "$company report - $name - $date" `
-BAH `
-Body $mail_customer
}
$mail += $mail_customer
$mailaddresses = "";
}
}
I get the email but it does not include the information that these lines should output, any ideas?
Script is called like this: powershell -file c:\temp\scriptname.ps1
Get-MailboxStatisticsrequires membership of theOrganization Managementrole-group in Exchange. Is the user account running the task member of the group?$mail_customerjust before the mail is sent, to check if it holds what you need ?