Sunday, August 15, 2010

Writing optical discs using IMAPI 2 in powershell

Today I’m going to show how to use Image Mastering API (IMAPI2) in powershell. I’m using that technique when need quickly to burn some data, in format, which is not exposed by default in Explorer. This also can be useful if you are developing some code on IMAPI2 and need some proof of concept, if that can be done using build-in windows image mastering API.
IMAPI2 is written using COM, so no additional wrappers/interops required in order to get it working in powershell. The advantage of IMAPI is the possibility to write to different medias, for example to CDRW So, let’s begin:
First of all you'll need to build in memory file system image, which will contain your files. There are few steps to achieve that:
Create file system object
PS C:\Temp> $fsi = New-Object -ComObject IMAPI2FS.MsftFileSystemImage
Select appropriate settings like File System type, revision and so on
To view current state of any object you can just type its name in PowerShell:
PS C:\Temp> $fsi
PS C:\Temp> $fsi.FileSystemsToCreate = 7
PS C:\Temp> $fsi.VolumeName = "MyImage"
Add files to your file system:
PS C:\Temp> $fsi.Root.AddTreeWithNamedStreams("C:\test\imt\data\2tracks")
Create result stream, that will contain your data in required format:
PS C:\Temp> $resultimage = $fsi.CreateResultImage()
PS C:\Temp> $resultStream = $resultimage.ImageStream
Actually at this step you can stop and save resulted image to the local hard disc, this will be a pure iso image.
To perform writing disc recorder needs to be initialized:
Enumerate available recorders through MsftDiscMaster2
PS C:\Temp> $dm = New-Object -ComObject IMAPI2.MsftDiscMaster2
Create DiscRecorder object
PS C:\Temp> $recorder = New-Object -ComObject IMAPI2.MsftDiscRecorder2
Initialize recorder with unique id from discmaster2
PS C:\Temp> $recorder.InitializeDiscRecorder($dm.Item(0))
Read more: OpticalStorage