' VMX Sort file 2 script 7/23/09 Matt Brinkhoff (matt.brinkhoff@nebraskatechnology.com)
' Sorts a VMX file by the text before the period for easy reading
' (also strips out comments and empty lines - if you like comments don't use this script!)

Const adVarChar = 200
Const MaxCharacters = 255
Const ForReading = 1
Const ForWriting = 2

' change to reflect the location of the VMX file you want to sort
strFileName = "o:\MyVirtualMachines\MyVM\MyVM.vmx"

' create recordset for sorting
Set DataList = CreateObject("ADOR.Recordset")
DataList.Fields.Append "SortField", adVarChar, MaxCharacters
DataList.Open

' read in the source file
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strFileName, ForReading)
Do Until objFile.AtEndOfStream
    strLine = objFile.ReadLine
    DataList.AddNew
    DataList("SortField") = strLine
    DataList.Update
Loop
objFile.Close

' backup the original file
'objFSO.CopyFile strFileName, "BackupOf_" & strFileName, true

DataList.Sort = "SortField"

' set the first line of the file
strText = "#!/usr/bin/vmware" & vbCrLf

DataList.MoveFirst

Do Until DataList.EOF
		strTemp = DataList.Fields.Item("SortField")
		if strTemp <> "" then
			strEval = left(strTemp, instr(strTemp,"="))
			if instr(strEval, ".") <> 0 then
				strCurrentFirstSection = left(strTemp, instr(strTemp, ".")-1)
			else
				strCurrentFirstSection = lcase(left(strTemp, 1))
				'strCurrentFirstSection = left(strTemp, instr(strTemp,"="))
			end if
			
			' strip out comments
			if left(strCurrentFirstSection,1) <> "#" then
				' add a blank line if we are on a different letter now
				if strLastFirstSection <> strCurrentFirstSection then
					strText = strText & vbCrLf
				end if			
				strText = strText & strTemp & vbCrLf
				strLastFirstSection = strCurrentFirstSection			
			End If


		end if
		DataList.MoveNext

Loop

Set objFile = objFSO.OpenTextFile(strFileName, ForWriting, True)

objFile.WriteLine strText
objFile.Close

msgbox "Sort Complete"
