任务计划程序中的Powershell脚本无法按预期工作

时间:2015-11-16 08:22:57

标签: powershell

我有一个脚本文件,当从ISE内部或从PowerShell窗口运行时,它可以正常工作。但是当通过" runas"运行任务调度程序时同一帐户只输出一半的数据。

经过一些故障排除后,我得出结论,部分代码无效:

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 = "";
        }
    }

我收到了电子邮件,但它不包含这些行应该输出的信息,任何想法?

脚本的调用方式如下:powershell -file c:\ temp \ scriptname.ps1

1 个答案:

答案 0 :(得分:1)

这是一个不经常升级的经典案例。代码中没有任何内容是错误的。

在任务计划程序中,确保为该任务勾选“以最高权限运行”,否则它将无效。