I'm just starting to learn how to code in Powershell. So, how can I do dis?
I searched the MS website but it is not clear...
PowerShell has no dedicated command for emitting a beep.
Therefore, use [Console]::Beep(), which you note as an option. This relies on the fact that you have virtually unlimited access to .NET APIs from PowerShell:
[Console]::Beep()
An alternative, available in Windows PowerShell v5.1 (the latest and last version - not sure about earlier ones) and in all versions of PowerShell (Core) 7, is to use escape sequence `a, representing the so-called BEL (BELL) character, inside an expandable string ("...").
Write-Host -NoNewLine "`a"
Note:
While "`a" alone would work too, it would also print a newline (which Write-Host -NoNewLine avoids).
Printing the BEL character to the console (terminal) rather than calling [Console]::Beep() (which uses the WinAPI) has one advantage: in terminal applications that support it, such as Windows Terminal, a visual indicator that the "bell was rung", so to speak, is shown in the window / tab title, which is helpful in situations where the sound is muted and/or you've been away from the terminal.
These will play the default system sounds.
[System.Media.SystemSounds]::Asterisk.Play()
[System.Media.SystemSounds]::Beep.Play()
[System.Media.SystemSounds]::Exclamation.Play()
[System.Media.SystemSounds]::Hand.Play()
[System.Media.SystemSounds]::Question.Play()
Playing the rest of the Sound control panel events is much more complicated and not as easily accessed as these five defaults. It's "possible" but I've not yet come across anything that packages it up nicely.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With