Search

Thursday, 06 September 2007

Fun with Powershell

First a warning, this posting is a bit more technical than the usual variety.

One of the useful/cool features of Powershell is the ability to create a .Net Framework object. This could be any object not just the ones supplied by the framework, such as one that you've created yourself or a third party object. The problem is that only the base class library of the .Net Framework seems to be loaded by default, so before any other object that you want to create can be created you must load the assembly it is declared in.

I wanted to see if I could get my computer to 'talk' by using Powershell and the managed speech API, which is not loaded by default so I had to load it into the shell to make its classes available. To do this you must issue the following command:

PS C:\> [Reflection.Assembly]::LoadFile('C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\System.Speech.dll')

This invokes the static method 'LoadFile' of the Assembly class, the square brackets tell the shell to get an instance of that type and the double colon indicates that a static method is to be invoked. The method itself requires the full path of the assembly to be loaded, which in this case is the managed speech API.

In order to get the computer 'talking' I had to create an instance of a speech synthesizer object and to do that I used the following command:

PS C:\> $v = new-object System.Speech.Synthesis.SpeechSynthesizer

That creates an instance of the object and places into a variable called $v. With the object created the fun bit can begin by calling the 'Speak' method like so:

PS C:\> $v.Speak('Hello, World')

Of course you can put whatever you like between the quotes, have fun!

Finally, I should point out that the managed speech API is supplied with Windows Vista, I'm not sure if its available on Windows XP.

Comments
To leave a comment please login
Register