Power shell+Task scheduler: auto tạo email mới theo lịch

 

1. Tạo 1 template email, nên tạo template để format , hoặc sau này cần cập nhật format,nội dung sẽ dễ hơn là chỉnh trong code

2. Mở notepad, copy đoạn code này vào, tùy chỉnh theo thực tế, lưu dưới đuôi .ps1


$Outlook = New-Object -ComObject Outlook.Application

# Đường dẫn template .oft

$TemplatePath = "C:\Users\PKUser\AppData\Roaming\Microsoft\Templates\Daily Report W12.oft"

# Lấy ngày hiện tại

$ReportDate = Get-Date

$WeekNum = [System.Globalization.CultureInfo]::CurrentCulture.Calendar.GetWeekOfYear($ReportDate, 2, 1)

$SubjectDate = $ReportDate.ToString("MM/dd/yyyy")

# Tạo email từ template

$Mail = $Outlook.CreateItemFromTemplate($TemplatePath)

# Cập nhật Subject

$Mail.Subject = "$SubjectDate Daily Report W$WeekNum"

# Hiển thị email

$Mail.Display()

# ÉP Outlook lên trên cùng

Start-Sleep -Milliseconds 500 # Chờ nửa giây cho chắc

$OutlookWindow = $Outlook.ActiveInspector.Window

$OutlookWindow.Activate()

Add-Type @"

using System;

using System.Runtime.InteropServices;

public class Win32 {

    [DllImport("user32.dll")]

    public static extern bool SetForegroundWindow(IntPtr hWnd);

}

"@

$hwnd = $OutlookWindow.Handle

[Win32]::SetForegroundWindow($hwnd)


3. Chạy thử code xem có hoạt động bình thường ko, sau đó vào task scheduler tạo 1 task với cài đặt như sau:





Action:powershell.exe



Chỗ "Add arguments" điền:
-ExecutionPolicy Bypass -File "D:\THANH\Temporately digital assessment\dailyemail.ps1"
Sau khi làm xong có thể chạy thử:



Nhận xét