Text-To-Speech using PowerShell

Just a little fun thing for a Friday, text-to-speech! We used this many years ago at the office, sending this to the laptop of a colleague and having fun while he’s trying to figure out where the voice is coming from ๐Ÿ™‚

Table Of Contents
show

How it works

There is a System.Speech assembly which can be used to convert text to speech, I made an Invoke-TextToSpeech function that accepts a -Text and a -Computername parameter. The -Computername starts an Invoke-Command to the computer name that you specify and starts talking on the remote computer, it doesn’t have a volume control function (Yet, if anyone knows how… Let me know! ) so the speaker shouldn’t be muted on that target ๐Ÿ™‚

Below is an example for running it locally:

Invoke-TextToSpeech -Text 'PowerShell is fun'

The voice is based on your local setting, in my case, it sounds pretty good in English. You can also output text from a variable in your script by running:

$variable | Invoke-TextToSpeech

In the example below it connects to a remote computer (Laptop-001) and outputs the text to that speaker:

Invoke-TextToSpeech -Text 'PowerShell is fun' -Computername Laptop-001

Note: There could be WinRM/Firewall settings preventing this on the remote computer

The script

Below is the Function that I made, run it in your PowerShell session, and have fun ๐Ÿ™‚

function Invoke-TextToSpeech {
    param (
        [parameter(Mandatory = $true, ValueFromPipeline = $true)][ValidateNotNullOrEmpty()][string]$Text,
        [parameter(Mandatory = $false)][string]$Computername
    )
    
    #If Computername is not specified, run local convert text to speech and output it
    if (-not $Computername) {
        try {
            Add-Type -AssemblyName System.Speech
            $synth = New-Object -TypeName System.Speech.Synthesis.SpeechSynthesizer
            $synth.Speak($text)
        }
        catch {
            Write-Warning ("Could not output text to speech")
        }
    }

    #try to connect to remote computer, convert to speech and output it
    if ($computername) {
        try {
            Invoke-Command -ScriptBlock {
                Add-Type -AssemblyName System.Speech
                $synth = New-Object -TypeName System.Speech.Synthesis.SpeechSynthesizer
                $synth.Speak($Using:Computername)
            } -ComputerName $Computername -ErrorAction Stop
        }
        catch {
            Write-Warning ("Could not connect to {0}" -f $Computername)
        }
    }
}

Download the script(s) from GitHubย here

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.