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"
- Chọn "Create Basic Task"
- Đặt tên & mô tả, nhấn Next
- Chọn "Daily", đặt thời gian
- 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)
- Program/script:
- Hoàn thành và kiểm tra lại
Nhận xét
Đăng nhận xét