Tự động copy latest file+mở copied 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 path
$destinationFolder = "D:\THANH\DAILY REPORT"  # destination folder

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

if ($latestFile) {
    # create new file with name "_copy"
    $fileNameWithoutExtension = [System.IO.Path]::GetFileNameWithoutExtension($latestFile.Name)
    $fileExtension = [System.IO.Path]::GetExtension($latestFile.Name)
    $newFileName = "$fileNameWithoutExtension`_copy$fileExtension"
    $destinationPath = Join-Path -Path $destinationFolder -ChildPath $newFileName

    # Copy file 
    Copy-Item -Path $latestFile.FullName -Destination $destinationPath -Force

    # open file copy
    if (Test-Path $destinationPath) {
        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/script: powershell.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