Had need to do this recently, and as per usual with powershell, it was kind of easy, but there were a few fiddly bits that don’t appear to have been thought through by the designers.
Note that as the title of this post states, this is Server 2012/Windows 8 and upwards. Won’t work on Windows 7/Server 2008 R2 even with the latest PowerShell v3.0 (unless they retro-fit it via a hotfix/service pack in the future). It’s an OS feature that can be accssed via PowerShell, not a PowerShell feature.
So, mounting a .ISO image is easy:
$ImagePath = "\\server\share\folder\mydvdimage.iso" Mount-DiskImage -ImagePath $ImagePath -StorageType ISO
The -StorageType ISO is optional by the way, but I found it so am using it.
Look in Windows Explorer, et voila, your ISO is now mounted and has a drive letter – access it as if it were a real CD/DVD in a physical drive, but probably with better access times.
But you can do that via the GUI by right-clicking on the ISO and choosing “Mount”. We’re doing this in a PowerShell script, and will no doubt be wanting to access that mounted ISO in the same script. Ho hum, what’s the drive letter that it’s been mounted as then? Maybe we can pick the drive letter to mount it as via the Mount-DiskImage command? The answers are “no idea” and “no“. Not exactly helpful is it?
My method for getting the drive letter is as follows:
$ISODrive = (Get-DiskImage -ImagePath $ImagePath | Get-Volume).DriveLetter Write-Host ("ISO Drive is " + $ISODrive)
If you’ve not run it yet, this just gives you the letter, no colon or backslash, so if you want to use the drive letter you’ll need to add those as you build up the path to whatever you’re accessing on the mounted ISO drive.
Once you’ve done accessing it, you’re probably going to want to dismount it again. Easy?
Dismount-DiskImage -DevicePath E:
Oops. Not so easy:
Dismount-DiskImage : Access is denied. At line:1 char:1 + Dismount-DiskImage -DevicePath E: + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : PermissionDenied: (MSFT_DiskImage:ROOT/Microsoft/.../MSFT_DiskImage) [Dismount-DiskImage ], CimException + FullyQualifiedErrorId : HRESULT 0x80070005,Dismount-DiskImage
So I RTFM. Dismount-DiskImage won’t let you dismount it by specifying the drive letter. In a way that makes sense, Mount-DiskImage seems to dislike drive letters, so why should Dismount-DiskImage be different? You have to dismount the drive by specifying the .ISO file path or by using the device path in the form \\.\CDROM (the latter of which we of course use all the time in Windows…not):
Dismount-DiskImage -ImagePath $ImagePath
The other way to dismount it, which does let you use the drive letter (albeit with a colon suffix) is to eject it like a physical CD/DVD drive:
$ShellApplication = New-Object -ComObject Shell.Application $ShellApplication.Namespace(17).ParseName($ISODrive.DriveLetter+":").InvokeVerb("Eject")
So there you go. Easy when you know how.