1

PowerShell - 即時回報處理進度

 2 years ago
source link: https://blog.darkthread.net/blog/ps-report-progress/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

PowerShell - 即時回報處理進度

calendar.svg 2021-07-14 10:55 PM comment.svg 0 eye.svg 1,083

要徹底惹毛急性子使用者,我有個好法子 - 讓程式跑慢一點,然後不要回報執行進度,等上幾次,對方便會變身浩克怒摔滑鼠鍵盤,嚴重一點說不定會氣急攻心中風身亡,別人我不敢說,這招對我絕對有效。

反之,開發程式遇到等待的耗時作業,即時回報處理進度可大大安撫使用者心情,因而願意耐心等待,依經驗,只要保持幾十秒內數字跳一下(即便灌票作假也罷),使用者頂多嫌你程式慢,不會罵你程式爛。

大家使用 PowerShell 時一定有看過這種下完指令冒出來的藍色進度條,

今天來說說怎麼為我們的程式加上類似效果。

其實加一個指令就搞定 - Write-Progress! Activity 參數為作業說明,Status 為即時進度說明文字,PercentComplete 為百分比數字 (0-100),另外還有些進階用法,像是巢狀顯示(總進度與目前步驟進度)... 等等。

Function RunSlowProcess([int]$count) {
    $sheep = @()
    for ($i = 1; $i -le $count; $i++) {
        Start-Sleep 1
        Write-Progress -Activity "數羊中" -Status "第 $i 隻羊" -PercentComplete ($i / $count * 100)
        $sheep += $i
    }
    "數完收工-" + $sheep
}

RunSlowProcess (Read-Host "要數多少隻羊?")

實測結果如下:(進度條會出現在命令列視窗第三列的位置)

反之,如果要反覆執行該指令,每次時間很短,不想一直看到進度條出現消失閃了又閃,則可設定 $ProgressPreference = "SilientlyContinue" 將其隱藏。

and has 0 comments

Comments

Be the first to post a comment

Post a comment

Comment
Name Captcha 99 - 24 =

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK