Tự động copy, đặt tên theo format và mở latest file theo lịch với Task scheduler+ Powershell

Case: Mỗi ngày, cần tạo 1 file excel mới từ latest file trong  thư mục cố định.




Mở notepad, copy code dưới vào và lưu dưới đuôi PS1

$sourceFolder = "D:\THANH\DAILY REPORT"   # original folder
$destinationFolder = "D:\THANH\DAILY REPORT"  # destination folder

# Get current date and week number
$currentDate = Get-Date
$weekNumber = [cultureinfo]::InvariantCulture.Calendar.GetWeekOfYear($currentDate, [System.Globalization.CalendarWeekRule]::FirstFourDayWeek, [DayOfWeek]::Monday)
$weekNumberFormatted = $weekNumber.ToString("00") # Ensure two-digit format
$formattedDate = $currentDate.ToString("yyyyMMdd")

# Construct new file name
$newFileName = "ERPTeam-Thanh-DailyReport-W$weekNumberFormatted-$formattedDate.xlsx"
$destinationPath = Join-Path -Path $destinationFolder -ChildPath $newFileName

# Check if the file already exists
if (Test-Path $destinationPath) {
    Start-Process "EXCEL.EXE" -ArgumentList "`"$destinationPath`""
    return
}

# Get latest excel file
$latestFile = Get-ChildItem -Path $sourceFolder -Filter "*.xlsx" | Where-Object { -Not $_.PSIsContainer } | Sort-Object LastWriteTime -Descending | Select-Object -First 1

if ($latestFile) {
    # Copy file
    Copy-Item -Path $latestFile.FullName -Destination $destinationPath -Force
    Start-Process "EXCEL.EXE" -ArgumentList "`"$destinationPath`""
}




Mở "Task Scheduler"

  1. Chọn "Create Basic Task"
  2. Đặt tên & mô tả, nhấn Next
  3. Chọn "Daily", đặt thời gian 
  4. Chọn "Start a Program", nhập:
    • Program/scriptpowershell.exe
    • Add arguments-ExecutionPolicy Bypass -File "C:\Path\To\Script.ps1" (đổi thành đường dẫn script bạn lưu)
  5. Hoàn thành và kiểm tra lại

6. Chạy thử: Chuột phải vào task=>Run






Nhận xét