Wednesday, November 13, 2013

Going home on time even with PowerShell script running long

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 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

1 comment:

  1. Love the real-world narration of a problem and a solution. Wish there was WAY more of this. Sometimes I can't seem to understand the reasoning behind choosing this solution over another. Thank you! AND you just taught me "while", which I have never looked at until today!