ur

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.

Capture1.JPG

 

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.


√-1 2^3 ∑ π, and it was delicious!

Share this post


Link to post
Share on other sites

Hi.

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!"
    exit
}


$VIserver="VirtualCenterServerName"

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

$SnapsExist=$true
$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 = ""
   }
   $SnapsExist=$false
}
$Report = $Report | 
    Select VM,Name,Description,Size,Created | 
    ConvertTo-Html -Head $Header -PreContent $("<p><h2>Snapshot Report - $VIServer.<br>" + $TimeString + "</h2></p><br>")

$FTstyle = @"
<body>

<style type="text/css">
        .TFtable{
                width:100%;
                border-collapse:collapse;
        }
        .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;
        }
</style>
"@


$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)."
    $msg.Attachments.Add($att)
    $smtp.Send($msg)
    $att.Dispose()
}

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

    • CygnusX1
      By CygnusX1
      Hello, 
      I have a dialog box that pops up during an install on a foreign OS. In this case Spanish. The dialog displays a message the program being installed needs to install .Net, CRT, and C++. When inspected the dialog it seems normal. I can get control IDs, Text, Position, everything. But when I try to have AutoIt interact with it e.g. move it, click a button, click on a control, ControlGetFocus, Send("{TAB}"), ControlClick(). Nothing works. What even weirder is I can WinActivate the dialog but then can't move the mouse with MouseMove. If I don't WinActivate(), I can use the MouseMove() function. I can not figure out how to interact with the dialog box.
      Any thoughts on a way to interact with this dialog box?
      Thanks.
       
       
       

    • TheSaint
      By TheSaint
      I had a need, and so I developed.
      Before I did that though, I did a quick search of the forum, and found a few things, but none seemed to suit what I really wanted ... though to be honest, I did not investigate them deeply or search extensively. In any case, I am not very good at modifying the code of others, nor do I enjoy doing so, so in the end I decided it was best to start from scratch ... re-inventing the wheel perhaps, but a wheel I feel a certain degree of comfort with. I also thought about Maps, but don't know enough.
      _IniString Functions (was Ini_InMem)
      Ini in memory
      Settings INI - Read/Write once to the disk
      INI File Processing Functions
      ... sure to be others.
      As with all my stuff, feel free to use (no guarantees) or modify ... just give me credit where due.
      I always go for the quick & simple approach, as those who know me here, are well aware, so without a doubt, my code could be improved - sped up, RegExp used, etc. So feel free to do that, and convert into a proper UDF, if you want, following best practices etc, as I am sure others will appreciate it.
      Recently, I have come upon a need to extract data from an approximately 50 Mb downloaded Index file, just extracting the few elements I need, and storing them in an INI file. It is quite a time consuming process, especially on my underpowered Netbook, which is where I am using the program I built. I have been considering ways to speed up things. Two good sounding methods, out of several possibles, have come to mind - 1) RAM Disk and 2) Virtual INI processing. That last being a better option, when sharing code (program) with others.
      Another method, which I am currently using, that did give me some measurable benefit, was to download the almost 50 Mb Index file in Stages (i.e. 30 x 1.4 Mb roughly), extracting data from each in turn. I have also considered extracting to 10 (or 11) separate INI files, rather than the single large INI file (4~5 Mb), as things noticeably slow up as the INI file increases in size ... obviously due to writing time.
      I can't really speed up the extraction process, but that last method may speed up the writing stage.  However, it would require significant program changes, and perhaps not gain me much benefit. To complicate things, there are too many Section names (Index ID's) for the IniReadSectionNames command, so I have had to split them off into their own (read/write) line-by-line index file, and create code to deal with duplicates. When read, Index ID's and Titles populate a Listbox control in a user GUI.
      So at this point in time, it seems best to use the Virtual INI approach to gain a significant reduction in time taken. For my own specific use, with my slow Netbook, I may also use a RAM Disk.
      Due to the aforementioned INI issues, and lack of available specific data, probably because it is always  program concentric, I have created an ASCII Checker program, which I guess you can say, is AutoIt  concentric. Because others may also find it handy, I am providing it here. NOTE - As yet, I am only aware that Escape characters exist, but have not investigated or catered for them in any way.
      ASCII Checker.zip

      The Virtual_INI_UDF is still a work in progress, though I have done most of the functions now, with the working but incomplete _Ini_Test function, still requiring changes etc from the information gleaned by the ASCII Checker program.
      Here's something to play with meanwhile.
      Updated files (24th February 2017)
      Virtual_INI_UDF.au3  NEW
      Example.au3 (23rd February 2017)
      All pretty basic, but managed to load my 4 Mb INI file (seemingly ok, but took a few seconds) ... though I have only worked with much smaller testing ones so far.
      P.S. While I have done a fair amount of testing, it has been pretty basic, and mostly limited to the examples provided. Testing has definitely not been extensive.
       
    • VIP
    • 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?