Powershell中Finally语句用法示例
在之前的小技巧中,我们曾经引入过,一个有声的进度条。在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() }
相关推荐
huha 2020-10-16
lianshaohua 2020-09-23
higheels 2020-08-03
ZoctopusD 2020-08-03
酷云的csdn 2020-08-03
higheels 2020-07-27
liushun 2020-06-28
zhendeshifeng 2020-06-22
Sabrina 2020-06-11
CARBON 2020-06-03
CARBON 2020-06-01
DBATips 2020-05-31
higheels 2020-05-29
applecarelte 2020-04-15
Yyqingmofeige 2020-03-28
yoshubom 2020-03-06
Yyqingmofeige 2020-03-02
SciRui 2020-02-26