在之前的小技巧中,我们曾经引入过,一个有声的进度条。在PowerShell正在做某项忙碌的任务时,可以一直让它播放某段音乐。代码如下:
# 在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()
脚本本来运行正常,但是当你终止了它,比如使用ctrl+C来终止,此时脚本运行立马结束。最后一行的$player.Stop()来不及执行,提示声音仍旧在余音绕梁,三日不绝。
解决办法,将最后一句收尾工作的$player.Stop()放在Finally语句中:
# 在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()
}