SoFunction
Updated on 2025-03-10

Example of usage of the Finally statement in Powershell

In the previous tips, we have introduced an audio progress bar. When PowerShell is doing a busy task, you can keep playing a certain piece of music. The code is as follows:

Copy the codeThe code is as follows:

# Find the wav audio file you want to give to the available wav audio file under the 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 $WAVPath
$()
  
1..100 | ForEach-Object {
 Write-Progress -Activity 'Doing Something. Hang in' -Status $_ -PercentComplete $_
 Start-Sleep -MilliSeconds (Get-Random -Minimum 300 -Maximum 1300)
 }
$()

The script is running normally, but when you terminate it, such as using ctrl+C to terminate it, the script run ends immediately. The last line of $() was not enough to be executed, and the prompt sound was still lingering in the lingering sound, and it lasted for three days.

Solution: Put $() of the last sentence to finish work in the final statement:

Copy the codeThe code is as follows:

# Find Wav Audio in Windows folder
$WAVPath = Get-ChildItem -Path $env:windir -Filter *.wav -Recurse -ErrorActionSilentlyContinue |
Select-Object -First 1 -ExpandProperty FullName
 
# Load and play
 
$player = New-Object $WAVPath
 
try
{
 
  $()
   
  1..100 | ForEach-Object {
    Write-Progress -Activity 'Doing Something' -Status $_ -PercentComplete $_
    Start-Sleep -MilliSeconds (Get-Random -Minimum 300 -Maximum 1300)
  }
}
 
finally
{
  $()
}