Stories from the PowerShell Trenches: Day 3

Adam Bertram

Adam Bertram

Read more posts by this author.

For day 3 of our Stories from the PowerShell Trenches series we have Tim Curwick. Tim has a blog (like all of you should!) and posted this awhile back. With permission, I’m reproducing it here but if you’d like to check out all the other great information Tim puts out head on over to his blog.

It was toward the end of my day after most of the users were gone when I decided to take the opportunity to briefly shut down an old virtual machine and compact the disks. It was running on a Hyper-V 2012 host, so you can’t compact the disks through the GUI. (It will let you try, and it won’t throw any errors, but it won’t actually compact anything.)

So I just tweaked a little snippet of code I had lying around, and let it fly. You have to mount the disks read only, run the compact, then dismount the disks.

$Paths = (Get-ChildItem "D:\Virtual Machines\Server27" -Recurse -Include "*.vhd*" ).FullName
ForEach ($Path in $Paths) {
    Mount-VHD $Path
    Compact-Disk $Path
    Dismount-VHD $Path

It mounted the first disk and zipped right through the compact. Then it mounted the second disk.

Uh oh. Apparently there was some work to be done on that one. It was going real slow. Not normally that big of a deal, but I had to leave shortly to catch the last bus home, and I need to be sure that the server was back on for users in the morning.

If I had anticipated this, I could have easily added a line at the end of my snippet to start the virtual back up, but I didn’t. If I had run it as a job, I could have another script watch for the job to finish, but I hadn’t. If I had more time, I could write something to query the disk system to see when the disk was dismounted, but that wasn’t something I could do off the top of my head in the time I had available.

I finally realized that if the disk was still mounted, it was visible to the file system. I opened Windows Explorer and found it was assigned drive letter E:. That made it easy.

I launched another PowerShell window, put in my one-liner, and went home to my lovely wife.

While (Test-Path E:\) {
    Sleep -Seconds 10
Get-VM Server27* | Start-VM

Subscribe to Adam the Automator

Get the latest posts delivered right to your inbox

Looks like you're offline!