Computer >> Hướng Dẫn Máy Tính >  >> Xử Lý Sự Cố >> Lỗi Windows

Thêm Delay (Pause) trong PowerShell: Lệnh tạm dừng đơn giản & Ví dụ thực tế

Hướng dẫn thêm pause (tạm dừng) vào script PowerShell.

Có nhiều cách thêm pause/wait command. Dưới đây các cách kèm ví dụ.

Thêm Delay (Pause) trong PowerShell: Lệnh tạm dừng đơn giản & Ví dụ thực tế

Cách thêm Pause vào PowerShell Script

  1. Mở PowerShell ISE từ Start menu
  2. Mở script PowerShell cần thêm pause
  3. Thêm dòng: start-sleep -Seconds 5 (thay 5 bằng số giây muốn pause) tại vị trí cần pause
    Thêm Delay (Pause) trong PowerShell: Lệnh tạm dừng đơn giản & Ví dụ thực tế
  4. Ví dụ trên thêm wait command ở dòng 3
  5. Lưu script → Chạy script

Cú pháp Start-Sleep:

Start-Sleep -seconds
Start-Sleep -milliseconds

Ví dụ

Start-Sleep -seconds 1.5  # Ngủ 1.5 giây
Start-Sleep -seconds 5    # Ngủ 5 giây
Start-Sleep -seconds 15   # Ngủ 15 giây

Start-Sleep -milliseconds 1.5  # Ngủ 1.5 ms
Start-Sleep -milliseconds 5    # Ngủ 5 ms
Start-Sleep -milliseconds 15   # Ngủ 15 ms

Cách thêm Pause có Countdown (đếm ngược)

Hiển thị countdown khi pause. Có thể ngắt bằng phím bất kỳ để script tiếp tục.

  1. Mở PowerShell ISE
  2. Mở script cần thêm pause
  3. Thêm dòng: timeout /t 15 (thay 15 bằng số giây) tại vị trí cần pause
    Thêm Delay (Pause) trong PowerShell: Lệnh tạm dừng đơn giản & Ví dụ thực tế
  4. Lưu script → Chạy script

Giao diện timeout:

Thêm Delay (Pause) trong PowerShell: Lệnh tạm dừng đơn giản & Ví dụ thực tế

Phương pháp thay thế

Thay timeout /t 15 bằng code sau:

1..60 | ForEach {
    Start-Sleep -s 1
    Write-Progress -activity "Timer Started: " -Status $_
}

Hiển thị countdown timer khác (mỗi giây cập nhật progress). Thay 60 bằng thời gian muốn đếm.

Thêm Delay (Pause) trong PowerShell: Lệnh tạm dừng đơn giản & Ví dụ thực tế

Cách thêm Pause với Popup Message

Hiển thị thời gian pause trong popup window.

  1. Mở PowerShell ISE
  2. Mở script
  3. Thêm code từ bài viết này
  4. Lưu → Chạy script

Giao diện popup:

Thêm Delay (Pause) trong PowerShell: Lệnh tạm dừng đơn giản & Ví dụ thực tế

Làm PowerShell Sleep với Progress Bar

Cách yêu thích: Sleep kèm progress bar.

  1. Mở PowerShell ISE
  2. Mở script
  3. Thêm code sau:
For ($i=0; $i -le 100; $i++) {
    Start-Sleep -Milliseconds 20
    Write-Progress -Activity "Sleeping For 20 Seconds" -Status "StatusString" -PercentComplete $i -CurrentOperation "CurrentOperationString"
}
  • Thay số 20 bằng giây muốn sleep
  • Thay text "Sleeping For 20 Seconds" tùy ý
  • Lưu → Chạy script

Giao diện progress bar:

Thêm Delay (Pause) trong PowerShell: Lệnh tạm dừng đơn giản & Ví dụ thực tế