Finally statement usage example in PowerShell _powershell

Source: Internet
Author: User
Tags sleep

In the previous trick, we have introduced, a sound progress bar. When PowerShell is doing a busy task, you can always let it play a piece of music. The code is as follows:

Copy Code code as follows:

# Locate the WAV audio file to be available under Windows folder
$WAVPath = Get-childitem-path $env: windir-filter *.wav-recurse-erroraction silentlycontinue |
Select-object-first 1-expandproperty FullName


# Load and Play

$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 ()

The script would have worked, but when you terminated it, like using CTRL + +, the script ended immediately. The last line of $player. Stop () Too late to execute, prompting the sound is still in buzzing, 3rd.

Solution, will be the last sentence to end the work of the $player. Stop () is placed in the finally statement:

Copy Code code as follows:

# Find WAV audio in Windows folder ask
$WAVPath = Get-childitem-path $env: Windir-filter *.wav-recurse-erroractionsilentlycontinue |
Select-object-first 1-expandproperty FullName

# Load and Play

$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 ()
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.