Add to Technorati Favorites
Welcome to ThePowerShellGuy.com Sign in | Join | Help

PowerShell, CdAudioDoor Module

I got nifty Add-Type trick from Tao Ma to open and close the CD door that he also posted on his blog here : http://blog.csdn.net/PowerShell/archive/2008/08/03/2761960.aspx

He is using Add-Type to do a P/Invoke call, Cool stuff ! right ?,

but as Jeffrey Snover mentioned here V2: Custom Enums using add-type is final, and we can only add the type once, hence you can not add it to the function

As the example already needs PowerShell CTP2 as it uses Add-Type, I did see it fit to translate into a module to solve this problem, also I made it a Script Cmdlet to show the use of ValidateSet to define the allowed options (Open,Closed) and it will enforce them :

$winnm = Add-Type -memberDefinition @"
  [DllImport("winmm.dll", CharSet = CharSet.Ansi)]
  public static extern int mciSendStringA(
  string lpstrCommand,
  string lpstrReturnString,
  int uReturnLength,
  IntPtr hwndCallback);
"@  -ErrorAction 'SilentlyContinue' -passthru -name mciSendString

cmdlet Set-CDAudioDoor {

  Param(
    [ValidateSet("open", "closed")][String[]]$Mode = 'open'
  )

  $winnm::mciSendStringA("set cdaudio door $mode", $null, 0,0)

}

As you save this code as CdAudioDoor.psm1 you can add it with add-module

Adding the Module will add the Cmdlet, also PowerShell takes care that the initialization code is being executed only once.

image

This is only a simple example of what Script Cmdlets and Modules can do, export specific script cmdlets only etc. but I think this is a nice example to peek at the great possibilities modules in PowerShell V2 can offer, for more info about Modules see also Jaykul's great post PowerShell Modules .

Enjoy,

Greetings /\/\o\/\/

Published Monday, August 04, 2008 1:44 PM by MoW
Filed under: , ,

Comments

No Comments
Anonymous comments are disabled