Option Explicit 

'Setup the variables
Dim WMIService
Dim VMList
Dim Hostname
Dim VMName
Dim VMAction
Dim compareType
Dim HOST
Dim VM
Dim VMStatus
Dim AllVMs

'Used to get all machines or just one
compareType = "="

'gets and sets the host name
Set HOST = WScript.CreateObject("WScript.Network")

'Get instance of 'virtualization' WMI service on the local computer
Set WMIService = GetObject("winmgmts:\\.\root\virtualization") 

'Get the arguments from the user input and go to the appropriate sub
if wscript.Arguments.count > 0 then
    Select case WScript.Arguments.Item(0)
        case "/start"
	        VMName = WScript.Arguments.Item(1)
	        VMAction = 2
	        compareType = "="
	        modifyVM
        case "/stop"
	        VMName = WScript.Arguments.Item(1)
	        VMAction = 3
	        compareType = "="
	        modifyVM
        case "/startAll"
	        VMName = HOST.ComputerName
	        VMAction = 2
	        compareType = "!="
	        modifyVM
        case "/stopAll"
	        VMName = HOST.ComputerName
	        VMAction = 3
	        compareType = "!="
	        modifyVM
        case "/list"
	        VMName = HOST.ComputerName
	        compareType = "!="
	        listVMs
        case "?","/?","-?","help","Help","/help","/Help"
	        helpMsg
        case else
	        helpMsg
    end select
else 
    helpMsg
end if

'Message to display when incorrect input or recived help switch
sub helpMsg
	AllVMs = "usage VMControl.vbs" & VBCr & VBCr & "/start <VM Name> - Starts the Virtual Machine" & VBCr & "/stop <VM Name> - Stops the Virtual Machine" & VBCr & "/startAll - Start all Virtual Machines" & VBCr & "/stopAll - Stop All Virtual Machines" & VBCr & "/list - List All Virtual Machines" 
end sub

'used to turn the VM on or off or saved
sub modifyVM
    Set VMList = WMIService.ExecQuery("SELECT * FROM Msvm_ComputerSystem WHERE ElementName" & compareType & "'" & VMName &"'") 

    For Each VM In VMList
        VM.RequestStateChange(VMAction)      	
        select case VMAction
	        case 3 VMStatus = "stopped"
	        case 2 VMStatus = "running"
	        case 32769 VMStatus = "saved"
        end select
	        AllVMs = VM.ElementName & " is " & VMStatus
    next
end sub

'used to get and display the VM's
sub listVMs
    Set VMList = WMIService.ExecQuery("SELECT * FROM Msvm_ComputerSystem WHERE ElementName" & compareType & "'" & VMName &"'") 

    For Each VM In VMList
        select case VM.EnabledState
	        case 3 VMStatus = "stopped"
	        case 2 VMStatus = "running"
	        case 32769 VMStatus = "saved"
        end select
	    AllVMs = AllVMs + VM.ElementName & " is " & VMStatus  & VBCr
	next
end sub

'Display a message of what happened or a help message
wscript.echo AllVMs