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...
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.
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
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.
© 2022 - 2025 — McMap. All rights reserved.
[console]::beep()
or justbeep()
??? – Atiptoe[console]::beep(500,300)
. The first one is frequency in hertz(ranging from 37 to 32767 hertz) and the second is duration in milliseconds. – Amylopsin