Powershell script not working with scheduled task

Eaven HUANG 2,191 Reputation points
2023-06-28T09:16:59.6366667+00:00

Dear Experts,

I tried to run below script via powershell command line and it worked just fine, but when I added it to my computer's scheduled task, nothing happened. How can I fix this issue? C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -executionpolicy bypass -noprofile -noninteractive -file "C:\ScheduledTasks\EmailFromOutlook.ps1"

I'm using my personal account to run the script and I'm the admin of our domain and I leave Outlook app running on my computer for the script to send emails.

Below is my working script to run with powershell command or ISE

# Compose email message
$subject = "Expiring MCS User Accounts within one month"
$body = @"
<p>Dear All,</p>

<p>Please be aware that the following user accounts are about to expire within one month. <br>
</p>

<p>Below are the expiring user account details:`r`n`r`n</p>

"@

$targetUsers | ForEach-Object {
    $user = $_
    $body += "<strong>Account Name:</strong> $($user.DisplayName)<br>"
    $body += "<strong>Email Address:</strong> $($user.EmailAddress)<br>"
    $body += "<strong>Job Title:</strong> $($user.Title)<br>"
    $body += "<strong>Department:</strong> $($user.Department)<br>"
    $body += "<strong>Expiration Date:</strong> $($user.AccountExpirationDate.ToString($expirationFormat))<br>"
    $body += "<br>"
}


# Create an Outlook application object
$outlook = New-Object -ComObject Outlook.Application

# Create a new mail item
$mail = $outlook.CreateItem(0)

# Set the recipient email addresses
$recipientEmailAddresses | ForEach-Object { $mail.Recipients.Add($_) }

# Set the subject and body of the email
$mail.Subject = $subject
$mail.HTMLBody = $body

# Send the email
$mail.Send()

# Display a confirmation message
Write-Host "Email sent successfully."


Windows for business Windows Server User experience PowerShell
Windows for business Windows Client for IT Pros User experience Other
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Olaf Helper 47,436 Reputation points
    2023-06-28T09:30:07.7666667+00:00

    -noprofile

    Why without profile? No profil = no Outlook settings like server name to use.

    I leave Outlook app running on my computer for the script to send emails.

    Doesn't matter, the scheduled task runs in a separate session.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.