lunix
lunix

Reputation: 361

Is there a way to beep in the console using POWERSHELL

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...

Upvotes: 7

Views: 10312

Answers (3)

wkearney99
wkearney99

Reputation: 119

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.

Upvotes: 3

mklement0
mklement0

Reputation: 437032

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.

Upvotes: 17

BentChainRing
BentChainRing

Reputation: 452

To add to the @mklement0 answer, there is an old Script Doctor post which highlights how you can change the tone/pitch and duration of the beep, as well.

To summarize (in case the link is removed):

[console]::beep() ## The default beep

[console]::beep(500, 300) ## param 1 is the tone; param 2 is the duration in ms; anything lower than 190, or higher than 8500 cannot be heard.

[console]::beep(2000, 500) ## a higher pitch, and longer duration

Upvotes: 5

Related Questions