在 .bat 作业完成运行后,如何让 Windows Powershell 播放声音?

har*_*cot 5 powershell notifications

正如标题所述,我在 powershell 中运行了一个 .bat 作业,当完成运行时,我希望发出声音通知。我想知道是否有一个 powershell 命令可以添加到我现有的 powershell 命令中。

sta*_*tor 22

除了boxdog此处)和TheGameiswar此处)的出色解决方案之外,我想提一下另一种可能性,它可以让您播放一些标准系统声音:

[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()
Run Code Online (Sandbox Code Playgroud)

另一种文本转语音方法

Add-Type -AssemblyName System.Speech
$synth = New-Object -TypeName System.Speech.Synthesis.SpeechSynthesizer
$synth.Speak("Hey $env:USERNAME, your job is finished!")
Run Code Online (Sandbox Code Playgroud)

定制化

有关完整详细信息,请阅读文档

嗓音

选择声音:

$synth.SelectVoice("Microsoft Zira Desktop")
Run Code Online (Sandbox Code Playgroud)

您可以通过以下方式查看可用的语音:

$synth.GetInstalledVoices() | Select-Object -ExpandProperty VoiceInfo
Run Code Online (Sandbox Code Playgroud)

速度

将语速设置为 -10(慢)到 10(快):

$synth.Rate = 5
Run Code Online (Sandbox Code Playgroud)

体积

将音量设置为 0(安静)到 100(大声):

$synth.Volume = 75
Run Code Online (Sandbox Code Playgroud)


The*_*war 13

你可以使用powershell自动变量来检查bat文件状态..按照 这个$?返回true,如果命令成功..

\n\n

下面是示例代码

\n\n
$a =Invoke-Command -ScriptBlock {\n\n& "C:\\temp1\\test.bat"\n}\n\nif($?){\n\n[console]::beep(500,300)\n\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

您还可以播放自定义声音,

\n\n
$PlayWav=New-Object System.Media.SoundPlayer\n\n$PlayWav.SoundLocation=\xe2\x80\x99C:\\Foo\\Soundfile.wav\xe2\x80\x99\n\n$PlayWav.playsync()\n
Run Code Online (Sandbox Code Playgroud)\n\n

参考文献:
\n https://devblogs.microsoft.com/scripting/powertip-use-powershell-to-play-wav-files/

\n

  • 请注意,如果您的系统声音设置为静音,则此功能不起作用。 (2认同)

box*_*dog 11

除了@TheGameiswar 建议的解决方案之外,您还可以通过让系统真正对您说话来获得一些乐趣:

# Create a new SpVoice objects
$voice = New-Object -ComObject Sapi.spvoice

# Set the speed - positive numbers are faster, negative numbers, slower
$voice.rate = 0

# Say something
$voice.speak("Hey, Harcot, your BAT file is finished!")
Run Code Online (Sandbox Code Playgroud)

注意:我只在 Windows 10 上测试过这个,所以它可能不适用于其他版本,但请试一试。

  • 当系统知道你的名字时(适用于域,如果不在域上,则可以使用环境变量作为用户名),这会更有趣: `(New-Object -ComObject Sapi.spvoice).speak("Hey, $(([adsi] "LDAP://$(whoami /fqdn)").givenName),您的 BAT 文件已完成!")` (10认同)