Option Explicit
'==========================================================================
'
'
' NAME: <vmware_compressor.vbs>
'
' AUTHOR: Mathieu CHATEAU
' DATE  : 18/04/2008
' VERSION:0.1
'
' COMMENT: <Defragment and shrink all VMDK files from a root folder>
'
'==========================================================================
Dim VmWareInstallFolder,VmdkRootFolder

'VmWare Workstation installation Folder
VmWareInstallFolder="C:\" & """" & "Program Files (x86)" & """" & "\VMware\" & """" & "VMware Workstation" & """"

'Where are all these vmdk files to cleanup (recursive)
VmdkRootFolder="F:\vmware"

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Do not touch from here

Const OpenAsASCII      =  0
Const FailIfNotExist   =  0
Const ForReading       =  1
Dim sTemp, sTempFile, objShell, objFSO,f,f1,sf,fc,fFile,sResults
Set objShell = CreateObject ("wscript.shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
sTemp = objShell.ExpandEnvironmentStrings("%TEMP%")
sTempFile = sTemp & "\vmwarecleaner.tmp"

ShowFolderList(VmdkRootFolder)

Function ShowFolderList(folderspec)
	Dim f1
	Set f = objFSO.GetFolder(folderspec)
	Set sf = f.SubFolders
	For Each f1 in sf
		ShowFolderList(f1.path)
		ShowFileList(f1.path)
	Next
End Function

Function ShowFileList(folderspec)
	Set f = objfso.GetFolder(folderspec)
	Set fc = f.Files
	For Each f1 in fc
		if instr(1,f1.name,".vmdk",1) then
			wscript.echo "#################################################"
			wscript.echo "Defrag: " & f1.path
			objShell.run "%comspec% /c " & VmWareInstallFolder & "\" & "vmware-vdiskmanager.exe" & " -d " & f1.path & " >" & sTempFile, 0 , True
			Displaylog
			wscript.echo "Shrink: " & f1.path			
			objShell.run "%comspec% /c " & VmWareInstallFolder & "\" & "vmware-vdiskmanager.exe" & " -k " & f1.path & " >" & sTempFile, 0 , True
			Displaylog
		End if
	Next
End Function

Function Displaylog
	Set fFile = objFSO.OpenTextFile(sTempFile, ForReading, FailIfNotExist, OpenAsASCII)
	sResults = fFile.ReadAll
	fFile.Close
	objFSO.DeleteFile(sTempFile)
	wscript.echo sResults
End Function

