I’m scheduling script if windows scheduled task is disabled from the given list then send email to me with Taskname in email subject and Taskinfo in body.
Email part is working fine
only I’m unable to format email body with disabled scheduler name and add disabled task name in to subject.
Please help me to format email body and add disabled task name to subject.
Here is my script-
$tasknamelist=Import-Csv"C:\Documents\task.csv"
foreach ($task in $tasknamelist){
$service=Get-ScheduledTask-TaskName"$taskname"| select -ExpandPropertyState|Out-Stringif($task.State-eq "Disabled"){
$Body ="$service is not running"}else{Write-Host"$Body Task is enabled"|Out-Null}} $Body
$From ="xxx@outlook.com"
$To ="xxx@outlook.com"
$Cc ="xxxx@outlook.com"#$Attachment = "C:\temp\Some random file.txt"
$Subject =""
$Body ="$Body"
$computer = $env:computername
$SMTPServer ="outlook.office365.com"
$SMTPPort ="587"Send-MailMessage-From $From -to $To -Cc $Cc -Subject"Task Scheduler is disabled on $computer"`
-Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl `-Credential $cred
i want, if task is disabled from given list and condition true, email should trigger and in the email body, Task Name and Taskpath and task state should be added.
and in email subject line Task name should be added.
and if more than two task disabled, task name separated with comma or new line.
1)Task Name should be added to the Email subject, if multiple schedulers matches, name with commas added to subject.
2)and in the email body Disabled schedulers named added with new line.
3)In Body Task name and state and taskpath shold be added.
Okay good, where did you stuck? Did you try anything? In-fact by referring to the code above you can achieve what you want, please give it a try. Thank you.
This can be simplified a bit. You have not mentioned how many tasks you are auditing or how many computers you are auditing. If it was 5 tasks and 10 computers, you would get up to 50 emails. The first suggestion is to send a single email per computer, so you could do something like this:
$creds = Get-Credential
$computer = $env:COMPUTERNAME
#Specific tasks names we are auditing
#$taskChk = Import-Csv -Path "C:\Documents\task.csv" | Select -ExpandProperty Name
$taskChk = 'UpdateAssistant', 'Recovery-Check'
$tasks = Get-ScheduledTask | Where{$_.State -eq 'Disabled' -and $taskChk -contains $_.TaskName}
if ($tasks) {
$params = @{
From = "xxx@outlook.com"
To = "xxx@outlook.com"
CC = "xxxx@outlook.com"
Subject = "{0} tasks disabled on {1}" -f @($tasks).Count, $Computer
SmtpServer = "outlook.office365.com"
BodyAsHtml = $true
Body = ($tasks | ConvertTo-Html | Out-String)
Port = 587
UseSsl = $true
Credential = $creds
}
Send-MailMessage @params
}
This would give you a subject and body respectively:
This could also be a single email. You can loop through each computer, create a CimSession and remotely get the tasks. The goal would be getting an output like this: