Managing VMWare with AutoIT

3 posts in this topic

#1 ·  Posted (edited)

With the below command I am able to revert a virtual machine in vmware workstation to a snapshot mentioned.

$sVMPath = <path of the vmx file of virtual machine>

$sSnapshot = <snapshot name>

$Ret = RunWait(@ComSpec & " /c VMRun.exe -T WS revertToSnapshot ""$sVMPath$"" ""$sSnapshot$"" nogui", "", @SW_HIDE)

But the problem here is the virtual machine may contain multiple snapshots with same name because multiple users use same workstation and eventually they are keeping same name sometimes like below or in attachment.

Both snapshots are with same name and in GUI we can use them with no issue.



But with autoit or with vmrun command line it is showing error as 

Error: The name does not uniquely identify one snapshot

Could anyone please help me on this.

Edited by ur

Share this post

Link to post
Share on other sites

@ur I have moved your thread to the appropriate forum; please be mindful of where you post.

When you're dead, you don't know you're dead - it's only difficult for those that know you. It's the same way when you're stupid...

My Scripts: SCCM UDFInclude Source with Compiled Script, Windows Firewall UDF

Share this post

Link to post
Share on other sites


I don't use VM-Workstation, so I don't have a clue, if the VMware PowerCLI can be used with "Workstation" as well.

This script might give you a start to collect all the snapshots. Using the snapshot date, you can pick the latest one, and as powershell returns objects, you should be able to use the "youngest" snapshot later on to revert to that one.

if (get-pssnapin vmware* -erroraction silentlycontinue) {
    write "PowerCLI Extensions are available (OK)"
} else {
    write "PowerCLI Extensions don't seem to be available,"
    write "but required for this script!"


disconnect-viserver -confirm:$false -ea silentlycontinue
connect-viserver $VIserver

$time=get-date -uformat "%Y-%m-%d@%Hh:%Mm:%Ss"
$TimeFile=$time -replace ":","'"
$TimeString=$time -replace ":"," "
$TimeString=$TimeString -replace "@"," um "
$TimeString = "Stand: " + $TimeString   
$Report = Get-VM | Get-Snapshot | Select VM,Name,Description,@{Label="Size";Expression={"{0:N2} GB" -f ($_.SizeGB)}},Created
If (-not $Report)
{  $Report = New-Object PSObject -Property @{
      VM = "No snapshots found on any VM's controlled by $VIServer"
      Name = ""
      Description = ""
      Size = ""
      Created = ""
$Report = $Report | 
    Select VM,Name,Description,Size,Created | 
    ConvertTo-Html -Head $Header -PreContent $("<p><h2>Snapshot Report - $VIServer.<br>" + $TimeString + "</h2></p><br>")

$FTstyle = @"

<style type="text/css">
        .TFtable td{
                padding:7px; border:#4e95f4 1px solid;
        /* provide some minimal visual accomodation for IE8 and below */
        .TFtable tr{
                background: #b8d1f3;
        /*  Define the background color for all the ODD background rows  */
        .TFtable tr:nth-child(odd){
                background: #ffffff;
        /*  Define the background color for all the EVEN background rows  */
        .TFtable tr:nth-child(even){
                background: #ccffcc;

$SaveTo=$($env:temp + "\VMs-mit-Snapshots_" + $TimeStamp + ".html")

$R2 = $Report -replace "<body>",$FTStyle
$R3 = $R2 -replace "<table>",'<table class="TFtable">'
$R3 | out-file $SaveTo
Write-host "VMs with snapshots are to be found in this HTML Report:"
write-host $SaveTo
. $SaveTo

if ($SnapsExist -and (get-pssnapin *exchange* -erroraction silentlycontinue)) {
    $smtpServer = "YourMailServerInternalIP"
    $att = new-object Net.Mail.Attachment($SaveTo)
    $msg = new-object Net.Mail.MailMessage
    $smtp = new-object Net.Mail.SmtpClient($smtpServer)
    $msg.From = "VMs-with-Snapshots@your-corp.local"
    $msg.To.Add(([adsi]"LDAP://$(whoami /fqdn)").mail)
    $msg.Subject = "VMs with snapshots, as of " + $TimeString
    $msg.Body = "open separately (The Outlook 2010 Preview Feature won't display this HTML properly)."

Regards, Rudi.

Earth is flat, pigs can fly, and Nuclear Power is SAFE!

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Similar Content

    • Trong
    • tazdev
      By tazdev
      Recently I have had to deal with a lot of customers who want to send documents to a share on their own PC. Keep in mind I always recommend using a server for SMB shares however, some people don't have a server or enough people to warrant having a server. I made the following so that my technician can have this on a flash drive and it will create a share exactly the same way each time so I know what was done in case there is an issue. 
      It will create the share (If it exists then it does not change the share called scan)
      It will create the user (if the user exists it will not modify that user)
      It will create a password for that user (If the user exists it will not change anything)
      It will create a shortcut to the share on the desktop
      It will grant the user full rights to the share both in permissions and security
      I hope you find it useful. It can probably be made cleaner but it does work for me so I don't mess with it too much. It will also create a TXT doc on the screen for the tech to use and a TXT file on the flash drive as a backup so they will know what was done.
      BTW, I just realized that I have a myshortcut.vbs file that gets installed. The VBS is noted in the notes in the script so you can make it if you want or incorporate it.
      #cs   Creates a folder on the root of C: called scans Creates a local user scan on the PC Attempts to create a share called scans based on the folder above, if it already exists then it does nothing Adds full control to everyone adds scan user full permissions to the share Pops up a notepad with the information for the customer to save and the tech to read off or print out Since I do not know what the actual folder name is of the share I cannot create a shortcut Created on a workstations create a shortcut using the unc \\@computername\scans VBS Stuff in case I am on a PC that does not have the script: --------------------------------- set WshShell = WScript.CreateObject("WScript.Shell" ) set oShellLink = WshShell.CreateShortcut(Wscript.Arguments.Named("shortcut") & ".lnk") oShellLink.TargetPath = Wscript.Arguments.Named("target") oShellLink.WindowStyle = 1 oShellLink.Save --------------------------------- #ce   #include <array.au3> #include <string.au3> #include <FileConstants.au3> #include <MsgBoxConstants.au3> #include <File.au3>   ; Declare vars ----------------------------------------- #Region Declare Variables Global $ver = "1.051" Global $uName = "scan" Global $hName = @ComputerName Global $lPath = "C:\scans" Global $tFname = "deleteme.txt" Global $sName = "scans" Global $uPassword = "Scanningpass" Local $cntr = 1 Global $shareCmdE = "net share scans=" & $lPath & " /grant:everyone,FULL" Global $shareCmdS = "cacls " & $lPath & " /T /E /G " & $uName & ":f" Global $userCmds = "net user " & $uName & " " & $uPassword & " /ADD /FULLNAME:Scan_Acct" Local $iFileExists = FileExists ($lPath&"\"&$tFname) ; Get the customer name Global $cName = InputBox(" Customer Name", "Please enter the Customer Name:","","") Global $subject = """Scan setup for " & $cName & " <- Company""" Global $cFile = @ScriptDir & "\" & $cname & "\" & $cName & "_scans.txt" Global $txt = "Share name: \\" & @ComputerName & "\" & $sName & @CR & "User: " & $uName & @CR & "Password: " & $uPassword & @CRLF & "Please save for future reference" & @CR & "Version: " & $ver Global $txtEmail = """Share name: \\" & @ComputerName & "\" & $sName & " ""& vbCRLF & """ & "User: " & $uName & " ""& vbCRLF & """ & "Password: " & $uPassword & """ & vbCRLF & """ & "OS: " & @OSARCH & " - " & @UserName & " - " & @OSVersion & """ & vbCRLF & """ & "Version: " & $ver & " """   #EndRegion   #Region Start_of_Program FileInstall( "C:\mkshortcut.vbs", @ScriptDir&"\mkshortcut.vbs", 1) NameofCompany() If $iFileExists Then makeshare() Else FileOpen($lPath&"\"&$tFname,9) makeshare() EndIf FileClose( $cFile ) FileClose($lPath&"\"&$tFname) FileDelete($lPath&"\"&$tFname)   #EndRegion   Func NameofCompany() ;$nowild = 1 $nowildq = StringInStr( $cName, "?") $nowildstar = StringInStr( $cName, "*") $nowildbk = StringInStr( $cName, "\") $nowildfwd = StringInStr( $cName, "/") $nowild = $nowildbk + $nowildfwd + $nowildq + $nowildstar ;MsgBox (0,"Nowild", $nowild & @CRLF & "$nowildstar: " & $nowildstar) While $nowild <> 0 $nowildq = StringInStr( $cName, "?") $nowildstar = StringInStr( $cName, "*") $nowildbk = StringInStr( $cName, "\") $nowildfwd = StringInStr( $cName, "/") $nowild = $nowildbk + $nowildfwd + $nowildq + $nowildstar ;MsgBox (0,"Nowild", $nowild & @CRLF & "$nowildstar: " & $nowildstar) Global $cName = InputBox(" Customer Name", "Name cannot contain * ? / or \" & @CRLF & "Please enter the Customer Name:","","") $nowildq = StringInStr( $cName, "?") $nowildstar = StringInStr( $cName, "*") $nowildbk = StringInStr( $cName, "\") $nowildfwd = StringInStr( $cName, "/") $nowild = $nowildbk + $nowildfwd + $nowildq + $nowildstar ;MsgBox (0,"Nowild", $nowild & @CRLF & "$nowildstar: " & $nowildstar) WEnd ;MsgBox(0,"test", $nowild & @CRLF & $cname) EndFunc   Func makeshare() RunWait( @ComSpec & " /c" & $usercmds, @ScriptDir, @SW_HIDE) RunWait( @ComSpec & " /c" & $sharecmde, @ScriptDir, @SW_HIDE) RunWait( @ComSpec & " /c" & $sharecmds, @ScriptDir, @SW_HIDE) RunWait( @ComSpec & " /c" & "mkshortcut /target:""\\" & $hName & "\" & $sName & """ /shortcut:""ScannedDocs""", @ScriptDir, @SW_HIDE) FileCopy( @ScriptDir & "\ScannedDocs.lnk",@DesktopCommonDir & "\ScannedDocs.lnk") FileOpen ( $cFile, 9) FileWriteLine ($cFile, $txt) FileClose ($cfile) Run("notepad.exe") WinWaitActive("Untitled - Notepad") Send ( $txt ) FileDelete(@ScriptDir&"\ScannedDocs.lnk") FileDelete(@ScriptDir&"\mkshortcut.vbs") EndFunc
    • Second
      By Second
      Greetings, people of the interweb!
      I'm trying to get started on automating actions using the VMware API, but I reached a dead end.  I was trying out this example but it doesn't work for me at all. Line 9, Char 1, Object required: 'VixCOM'.
      All that I've done now is got a grasp of how the vmrun works via command line, but I do not find it enough for me.
      Could anyone point me at the correct direction or tell me what I'm doing wrong? (Please note that the script is in VBS, I want to get it working first, then continue translating it to AutoIT)
      Dim lib Dim host Dim job Dim vm Dim result Set lib = CreateObject("VixCOM.VixLib") ' Connect to the local installation of Workstation. This also initializes the VIX API. Set job = lib.Connect(VixCOM.Constants.VIX_API_VERSION, VixCOM.Constants.VIX_SERVICEPROVIDER_VMWARE_WORKSTATION, Empty, 0, Empty, Empty, 0, Nothing, Nothing) ' results needs to be initialized before it's used, even if it's just going to be overwritten. Set results = Nothing ' Wait waits until the job started by an asynchronous function call has finished. It also ' can be used to get various properties from the job. The first argument is an array ' of VIX property IDs that specify the properties requested. When Wait returns, the ' second argument will be set to an array that holds the values for those properties, ' one for each ID requested. err = job.Wait(Array(VixCOM.Constants.VIX_PROPERTY_JOB_RESULT_HANDLE), results) If lib.ErrorIndicatesFailure(err) Then ' Handle the error... End If ' The job result handle will be first element in the results array. Set host = results(0) ' Open the virtual machine with the given .vmx file. Set job = host.OpenVM("c:\Virtual Machines\vm1\win2000.vmx", Nothing) err = job.Wait(Array(VixCOM.Constants.VIX_PROPERTY_JOB_RESULT_HANDLE), results) If lib.ErrorIndicatesFailure(err) Then ' Handle the error... End If Set vm = results(0) ' Power on the virtual machine we just opened. This will launch Workstation if it hasn't ' already been started. Set job = vm.PowerOn(VixCOM.Constants.VIX_VMPOWEROP_LAUNCH_GUI, Nothing, Nothing) ' WaitWithoutResults is just like Wait, except it does not get any properties. err = job.WaitWithoutResults() If lib.ErrorIndicatesFailure(err) Then ' Handle the error... End If ' Wait until VMware Tools are running within the guest, with a 300 second timeout. Set job = vm.WaitForToolsInGuest(300, Nothing) err = job.WaitWithoutResults() If lib.ErrorIndicatesFailure(err) Then ' Handle the error... End If Set job = vm.LoginInGuest("vixuser", "secret", 0, Nothing) err = job.WaitWithoutResults() If lib.ErrorIndicatesFailure(err) Then ' Handle the error... End If Set job = vm.RunProgramInGuest("c:\myProgram.exe", "/flag arg1 arg2", 0, Nothing, Nothing) err = job.WaitWithoutResults() If lib.ErrorIndicatesFailure(err) Then ' Handle the error... End If Set results = Nothing Set job = Nothing Set vm = Nothing host.Disconnect() ITypeInfo Viewer showed me that the object name is correct, but the variables are inaccessable using both VixCom object and VIxCOM.VixLib.
      Note: https://www.vmware.com/support/developer/vix-api/ SDK from here is also installed on the machine.
      I have VMware workstation 10
      Any thoughts?
    • grimmlock
      By grimmlock
      Good Morning,

      I copied a script from here and was able to get it so that when the screen is unlocked it displays a message, however what I would like to have happen is only the display a message once, but keep the script running at all times, and then every time the workstation is unlocked display a message.

      Here is what I have so far.

      Global Const $DESKTOP_SWITCHDESKTOP = 0x100 While 1 If _CheckLocked() = 0 Then msgbox(0, "", "Test") EndIf WEnd Func _CheckLocked() $hLockedDLL = DllOpen("user32.dll") $hDesktop = DllCall($hLockedDLL, "int", "OpenDesktop", "str", "Default", "int", 0, "int", 0, "int", $DESKTOP_SWITCHDESKTOP) $ret = DllCall($hLockedDLL, "int", "SwitchDesktop", "int", $hDesktop[0]) DllCall($hLockedDLL, "int", "CloseDesktop", "int", $hDesktop[0]) If $ret[0] = 0 Then $iLocked = 1 ElseIf $ret[0] = 1 Then $iLocked = 0 EndIf DllClose($hLockedDLL) If $iLocked Then Return 1 Else Return 0 EndIf EndFunc