在之前的小技巧中,我們曾經(jīng)引入過,一個有聲的進(jìn)度條。在PowerShell正在做某項忙碌的任務(wù)時,可以一直讓它播放某段音樂。代碼如下:
復(fù)制代碼 代碼如下:
# 在windows 文件夾下面找到要給可用的wav音頻文件
$WAVPath = Get-ChildItem -Path $env:windir -Filter *.wav -Recurse -ErrorAction SilentlyContinue |
Select-Object -First 1 -ExpandProperty FullName
# 加載并播放
$player = New-Object Media.SoundPlayer $WAVPath
$player.PlayLooping()
1..100 | ForEach-Object {
Write-Progress -Activity 'Doing Something. Hang in' -Status $_ -PercentComplete $_
Start-Sleep -MilliSeconds (Get-Random -Minimum 300 -Maximum 1300)
}
$player.Stop()
腳本本來運行正常,但是當(dāng)你終止了它,比如使用ctrl+C來終止,此時腳本運行立馬結(jié)束。最后一行的$player.Stop()來不及執(zhí)行,提示聲音仍舊在余音繞梁,三日不絕。
解決辦法,將最后一句收尾工作的$player.Stop()放在Finally語句中:
復(fù)制代碼 代碼如下:
# 在Windows文件夾找到Wav音頻問
$WAVPath = Get-ChildItem -Path $env:windir -Filter *.wav -Recurse -ErrorActionSilentlyContinue |
Select-Object -First 1 -ExpandProperty FullName
# 加載并播放
$player = New-Object Media.SoundPlayer $WAVPath
try
{
$player.PlayLooping()
1..100 | ForEach-Object {
Write-Progress -Activity 'Doing Something' -Status $_ -PercentComplete $_
Start-Sleep -MilliSeconds (Get-Random -Minimum 300 -Maximum 1300)
}
}
finally
{
$player.Stop()
}