David Wang published a great script for achieving following requested tasks:
- start / restore from saved state if machine is not running (preferably disconnected from network in order to preserve resources)
- run on the guest the VHD maintenance utility (manually done by mounting the ISO from the virtual server directory and pressing next on the guest)
- save state / ( shut down only if necessary for next stage)
- compact the VHD
Be sure to read the original post for comments and updates.