PowerCLI Scripting - create or remove automatic instant

It is a script noob question...

I have an ESXi4.1 host several VM that create twice daily snapshots. After a week or two, I have a TON of pictures to delete. I can manually run the commands below every week or two to remove all these clichés but its becoming a chore, so I would like to create a script that runs once a week to do a little cleaning. Trying to automate this process, I run a question after the "remove-snapshot" I need to channel into the question "[a] yest at all."

Not exactly, but it's pretty close to what my script does:

to connect-viserver < ip > - < user > - < password >

Get - vm | Get-snapshot | Remove-snapshot

????????? Question answer with 'A '?

output

Y at - it a simple way to pipe in this 'A '.

Any help is greatly appreciated.

All you have to do is to add at the end of the line - confirm: $false

connect-viserver  -user  -password 
get-vm | get-snapshot | remove-snapshot -confirm:$false

This indicates the command for you does not invite to respond every time.

Maish

VMware communities moderator

My Blog - @maishsk

Co-author of VMware vSphere Design

Tags: VMware

Similar Questions

  • PowerCLI Script Create Role in vCenter

    I'm looking for is a PowerCLI script to create a role in vCenter. I found this post, and I wonder if it can be adapted to my needs. What I need specifically is a script to create a role with all of the following privileges:

    System.Anonymous

    System.View

    System.Read

    Global.SetCustomField

    Datastore.AllocateSpace

    Network.Assign

    VirtualMachine.Inventory.Create

    VirtualMachine.Interact.PowerOn

    VirtualMachine.Interact.DeviceConnection

    VirtualMachine.Interact.SetCDMedia

    VirtualMachine.Interact.GuestControl

    VirtualMachine.Config.AddNewDisk

    VirtualMachine.Config.CPUCount

    VirtualMachine.Config.Memory

    VirtualMachine.Config.AddRemoveDevice

    VirtualMachine.Config.Resource

    VirtualMachine.Config.DiskExtend

    Resource.AssignVMToPool

    VApp.Import

    StoragePod.Config


    It is possible with a PowerCLI script?

    You can get the file to root like this

    Get-file-name of data centers

    The rest of your script seems ok.

  • PowerCLI script delete/create the snapshot in ESXi5.5

    Hello

    Last week, I upgraded one of my host of esxi5.1 to 5.5

    everythink works exepted one of my script powerCLI.

    On my host 5.5, I can't throw a snapshots of delete/create:

    Remove-Snapshot: 14/11/2013-13:45:37Remove-SnapshotCurrent permit

    or version ESXi prohibited the execution of the requested operation.

    At line: 1 char: 92

    + Get - VM | Get-Snapshot | Where {$_.} Created - lt ((Get-Date).) AddHours(-46))} | R

    eMove-Snapshot < < < <-confirm: $false

    + CategoryInfo: NotSpecified: (:)) [delete-screenshot], RestrictedV)

    ersion

    + FullyQualifiedErrorId: Client20_VMServiceImpl_RemoveSnapshot_ViError, VM

    ware.VimAutomation.ViCore.Cmdlets.Commands.RemoveSnapshot

    A feature has been remove en 5.5?

    Thank you

    I guess that's not possible. This has already been discussed in communities. Please take a look at this thread. https://communities.VMware.com/message/2211533

    ~ dGeorgey

  • How to start a PowerCLI Script automatically

    I'm looking for a way to automate a PowerCLI script start.  For example, starting with the most basic scripts such as:

    Get-VM-name MyVM

    I want to have a file that I can click on my desktop that starts PowerCLI, running connect-VIServer and connects to my server, gives the appropriate credentials to connect, then running my

    Get-VM-name MyVM

    script.  It could be a batch (.bat) windows file that would start with powershell and run a .ps1 file, in the process of passing all the arguments appropriate for authentication, etc. or another strategy.

    Take a look at this article.  Step 3 review the batch file to create and your authentication options.

    http://blogs.VMware.com/vipowershell/2009/09/how-to-run-PowerCLI-scripts-from-vCenter-alarms.html

    Dave

    VMware communities user moderator

    Now available - vSphere Quick Start Guide

    You have a system or a PCI with VMDirectPath?  Submit your specifications to Officieux VMDirectPath HCL.

  • Create jobs that runs a powercli script every day at 20:00

    Hi all

    I'm looking for a way to add a powercli script to cron or schduler so that it runs every day at 20:00 say... I found average windows wrt link below

    http://social.msdn.Microsoft.com/forums/SharePoint/en-us/e63d0776-b4aa-4ab6-885c-a41fd0c83a7c/create-job-that-runs-a-PowerShell-script-every-day?Forum=sharepointgeneralprevious

    Is there better way that this can be done for powercli as well?

    Thank you

    AFAIK, except if you have a few programming specifialised run SW, Windows Scheduler did a good job.

    BTW, Alan has also made a post on this, see running a scheduled task PowerCLI

  • Need a powercli script to create a new account a local administrator on all ESX and ESXi hosts in the vcenter

    Hi all

    If someone can help me with a powercli script to create a new account a local administrator on all ESX and ESXi hosts in the vcenter, create a role called admin and give all access except the root. This shoulb be past by a virtual centre.

    Very much appreciated to help him.

    Kind regards

    MelLvin

    I suspect that you posted your question to the wrong thread

    This requires only a minor change to the script above actually.

    Something like that

    $groupName = "group"$accountName = "user"$accountPswd = "password"$accountDescription = "A user"
    
    $esxlist = Get-VMHostforeach($esx in $esxlist){    Connect-VIServer -Server $esx -User root -Password "password"
    
        Try {      Get-VMHostAccount -Id $groupName -Group -ErrorAction Stop | Out-Null    }    Catch {      New-VMHostAccount -Id $groupName -GroupAccount | Out-Null    }
    
        $rootFolder = Get-Folder -Name ha-folder-root    Try{        $account = Get-VMHostAccount -Id $accountName -ErrorAction Stop |        Set-VMHostAccount -Password $accountPswd -Description $accountDescription -AssignGroups $groupName    }    Catch{        $account = New-VMHostAccount -Id $accountName -Password $accountPswd -Description $accountDescription -UserAccount -GrantShellAccess -AssignGroups $groupName    }
    
        $rootFolder = Get-Folder -Name ha-folder-root    New-VIPermission -Entity $rootFolder -Principal $account -Role admin
    
        Disconnect-VIServer -Confirm:$false}
    
  • remove automatic archivelog

    Hello everyone.

    I would be grateful if someone could confirm if my understanding of the below is correct.

    Let's say we have an application that stores its data in Oracle database 11 g 2.

    RMAN parameters are:

    CONFIGURE REDUNDANCY 1 RETENTION STRATEGY; # by default

    CONFIGURE BACKUP OPTIMIZATION # by default

    SET UP DEFAULT DISK DEVICE TYPE; # by default

    CONFIGURE CONTROLFILE AUTOBACKUP ON;

    CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO "%F" # by default

    SET UP THE DEVICE TYPE DISK PARALLELISM BACKUPSET BACKUP TYPE COMPRESSED 4;

    CONFIGURE BACKUP OF DATA TO DISK FILE TYPE DEVICE TO 1; # by default

    CONFIGURE BACKUP ARCHIVELOG FOR DEVICE TYPE DISK TO 1; # by default

    CONFIGURE MAXSETSIZE TO UNLIMITED; # by default

    CONFIGURE ENCRYPTION OF DATABASE # by default

    CONFIGURE THE ENCRYPTION ALGORITHM "AES128"; # by default

    CONFIGURE COMPRESSION ALGORITHM 'BASIC' AND 'DEFAULT' LIBERATION OPTIMIZE FOR TRUE LOAD; # by default

    CONFIGURE THE NONE ARCHIVELOG DELETION POLICY; # by default

    The application raises backups using RMAN script once per week serving as archivelogs and obsolete backups. Let's say that, at a given time (for some reason any), backups start to fail. Archivelogs you will develop and will not be purged because Oracle will not be one of them as being obsolete (all archivelogs will be required to perform the recovery since the last successful backup).

    Archivelogs continues to grow until DB_RECOVERY_FILE_ _Dest_size is reached and a few DB point will be national

    Please correct if I am wrong up to that point.


    At the bottom of the documentation:
    Configuration of RMAN environment

    "Restoring archived logs can be automatically deleted by the database or RMAN commands initiated by the user. Only newspapers in the field of quick recovery can be deleted automatically by the database. For files recovery logs stored in the area of fast recovery, the database keeps them as long as possible and automatically removes the qualifying newspapers when additional disk space is needed. »

    Because newspapers are not eligible for deletion (they are required for recovery since the last backup) in archive scenario above they will not be removed automatically.

    I'm looking for possible ways to prevent DB suspended due to filling FRA archive logs.

    My question is:

    1. is it possible to change the RMAN parameters above so that the archive logs are automatically disabled in above scenario? (It is acceptable to lose the ability to recover the database) or the only way is to create the RMAN script which will remove for example with force newspapers to archive older then a week. ?

    Thank you

    Greg

    I don't know if I understand your environment, but have answered your question, you can do a RMAN script with something like this "DELETE NOPROMPT ARCHIVELOG ALL"; scheduled to run hourly, daily (the best option for your). I suggest to create a script to make a backup of the archivelogs with clause "delete entry" (if you have a physical backup), but you said "lose the possibility of recovering the database is acceptable.

  • Change the PowerCLI Script to use the DRS and DRS storage

    Hello

    I have a PowerCLI script that specifies a host and a data store to create a new virtual machine, which has served us well. Now we have activated the DRS and DRS storage and I wonder what to change in order to take advantage of these features. Are there commands to specify a cluster and the cluster data store and let the DRS to decide the initial investment for a new virtual machine? At the moment we put all hosts and the warehouses of data as variables and use them in the line below.

    Thank you.

    $newVM = New-VM-name $NewVMname - VM $TemplateName Datastore - $datastore - VMHost $vHost - confirm: $false - location $myName

    You set a Datastorecluster?

    If Yes, then you can replace the value of parameter data with the datastorecluster object store.

    Replacing a VMHost with a cluster is not taken in charge I'm afraid.

    But you can use something like this

    New-VM-name TestVM Datastore - DSC - ResourcePool (Get-Cluster-name mycluster |) Get - Resourcepool - name of resources)

    This will automatically select the VMHost.

    The virtual machine appears in the root of the cluster.

    DSC is the name of a datastorecluster in the cluster mycluster

  • PowerCLI Script to the report on the failed VM jobs

    I figured out how to report on the events of VM (get-vievent), but no has no stains of VM. If a snapshot of the virtual computer fails, sometimes it never connect the events of the VM, but lists an error on the display of tasks. We are trying to monitor the clichés failed since its part of our backup solution.

    I was looking for a way to report these tasks/failure of events in a daily report, or simply add to the daily report of amazing Alan Renouf that we use.

    does anyone have any suggestions? For an example, see the attached screenshots. See how, in the view tasks, you have mistakes, but in the view of events, there is no errors.

    Any help would be great. Thank you!

    Jeff

    PowerCLI Script to the report on the failed VM jobs

    I figured out how to report on the events of VM (get-vievent), but no has no stains of VM. If a snapshot of the virtual computer fails, sometimes it never connect the events of the VM, but lists an error on the display of tasks. We are trying to monitor the clichés failed since its part of our backup solution.

    I was looking for a way to report these tasks/failure of events in a daily report, or simply add to the daily report of amazing Alan Renouf that we use.

    does anyone have any suggestions? For an example, see the attached screenshots. See how, in the view tasks, you have mistakes, but in the view of events, there is no errors.

    Any help would be great. Thank you!

    Jeff

    Hi Jeff

    I had exactly the same need to identify stereotypes having failed and drilled until SDK and LucD suggestions (thank you) to encode the following lines:

    $vmlist = Get-VM |sort Name
    
    foreach ($guestname in $vmlist)
    {
        $hours = 48 # Number of hours back
          $tasknumber = 999          # Windowsize of the Task collector
    $taskMgr = Get-View TaskManager
    
    # Create hash table. Each entry is a create snapshot task
    $report = @{}
    
    $filter = New-Object VMware.Vim.TaskFilterSpec
    $filter.Time = New-Object VMware.Vim.TaskFilterSpecByTime
    $filter.Time.beginTime = (Get-Date).AddHours(-$hours)
    $filter.Time.timeType = "startedTime"
    
    $collectionImpl = Get-View ($taskMgr.CreateCollectorForTasks($filter))
    
    $dummy = $collectionImpl.RewindCollector
    $collection = $collectionImpl.ReadNextTasks($tasknumber)
    while($collection -ne $null){
    $collection | where {$_.DescriptionId -eq "VirtualMachine.createSnapshot" -and $_.EntityName -eq $guestName} | %{
    if ($_.State -eq "Error") {
            write-host $_.EntityName
            write-host $_.StartTime
            write-host $_.State
            }
        else {
        }
    }
    $collection = $collectionImpl.ReadNextTasks($tasknumber)
    }
    $collectionImpl.DestroyCollector()
    
     }  
    

    This script displays the name of the virtual machines which met with an instant failure in the last 48 hours (a variable, you can change)

    This is just the beginning, because I want to count the shots failed and identify virtual computers that have more than 2 in 2 days

    Feel free to alter it at will.

    Enjoy

    Eric

  • PowerCLI script to migrate virtual machines to the new vCenter environment

    Hello world

    in the next few weeks, we need about migrate 700 VMs (Windows/Linux) server to a new environment (new vCenter, new hosts, but VMs will remain on same data warehouses). VMs will be migrated not in one batch, but rather from time to time (which, however, can understand the need to migrate some 10s of virtual machines at the same time).

    Cluster names and folder structure will be identical to the old and the new vCenters. As host in the new vCenter names differ from those in the old vCenter, thought to provide a table of 'translation', which tells the script to save a given VM on host B (new vCenter) when having been registered in order to host a (old vCenter) and so on.

    I thought writing a PowerCLI script which, broadly speaking, can accomplish the following steps:

    • Connect to vCenterOld and vCenterNew
    • Correspondence table of host to read from a file (see step "register VM vCenterNew below)

    Then, in a loop:

    • Ask VM name
    • Get the settings of the virtual machine: Datastore/path, network/Portgroup, HA restart priority, host, folder, note
    • View the parameters and the VM name and request confirmation migrate the virtual machine
    • Turn off VM (closed OS gracefully, but force power off if power status is still not equal 'off' after a time given)
    • To unsubscribe from VM vCenterOld (removal of inventory)
    • Registry of the VM to the data store vCenterNew (assumptions: same folder as vCenterOld, host names are different, but for each source in vCenterOld host a host of destination in vCenterNew for you join the virtual machine to can be provided, that is, CSV)
    • The value of VM portgroup (same name as in vCenterOld)
    • Set VM HA restart priority
    • PowerON VM
    • Wait / check the VM (for example, ping) connectivity / continue immediately if the virtual machine is accessible or after a certain time if the virtual machine is still inaccessible
    • Confirm that the virtual machine has been migrated successfully, OR ask the user to check the connectivity of the virtual machine

    Now to my questions:

    • Is anyone know about an existing script that does something similar or contains parts that can be useful to compile a script like this?
    • How can vCenter two connections at the same time been managed within a PowerCLI script - or doesn't work at all and a connect/disconnect to/from the two vCenters must be completed for each virtual computer?

    Many thanks for any help.

    The following seems to work for me

    $vm = Get-VM -Name MyVM$nic = Get-NetworkAdapter -VM $vm $vdPG = $nic | select -ExpandProperty NetworkName
    
    Get-VDPortgroup -Name $vdPG
    
  • Complete the VI Client with PowerCLI Script idle Sessions

    Hello gurus PowerCLI

    I searched the net for a script PowerCLI that would end all the VI client sessions that have been inactive for x period of time.  I found a post on the forums of VMware (http://communities.vmware.com/message/914858?z=zI0r8n) but had no luck with it.  I also found a script created by A.Mikkelsen, to http://www.amikkelsen.com/?p=384 , but that one does not work either.

    Here's the actual script by A.Mikkelsen that is based on code by LucD in the forum mentioned previously.

    BEGINNING

    ##################################################################################
    # The script terminates all sessions if idle idle user for more than xx #.
    #                             #
    # Created by: Anders Mikkelsen, 2010 #.
    ##################################################################################
    Claire
    # Add - PSSnapin VMware.VimAutomation.Core

    # $server = "vcenter server.
    # $user = "vcenter username.
    # $pwd = "password of vcenter.

    # Add 1 extra hour when, due to the difference of timestamp between MSSQL and Windows.
    # slow down time 5 hours = 360
    # 10 hours slowed = 660
    $intOlderThan = 60

    # Connect-VIServer $server - user $user-password $pwd
    # Connect-VIServer $server

    $svcRef = new-object VMware.Vim.ManagedObjectReference
    $svcRef.Type = 'ServiceInstance.
    $svcRef.Value = 'ServiceInstance.
    $serviceInstance = get-views $svcRef

    $sessMgr = get-view $serviceInstance.Content.sessionManager
    $oldSessions = @)
    {foreach ($sess in $sessMgr.SessionList)}
    If (($sess.)) (LastActiveTime) .addminutes ($intOlderThan) - lt (Get-Date)) {}
    $oldSessions += $sess. Key
    #write "$($sess.)". User name)'
    }
    }

    # Session terminal that are inactive for more than approved ($intOlderThan)
    $sessMgr.TerminateSession ($oldSessions)

    Disconnect-VIServer *-confirm: $false

    END

    The error message I get is:

    BEGINNING

    Exception calling 'TerminateSession' with '1' or the arguments: "it was not correct to specified parameters.

    "

    D:\Scripts\vc_terminate_idle_sessions.ps1:36 char: 26

    + $sessMgr.TerminateSession < < < < ($oldSessions)

    + CategoryInfo: NotSpecified: (:)) [], MethodInvocationException)

    + FullyQualifiedErrorId: DotNetMethodException

    END

    I should mention that my knowledge of PowerCLI is almost nothing, so any help in tweaking this script to make it work with PowerCLI 5.1 Release 2 and VC 5 U2 would be much appreciated.

    The error is caused by the fact that you are trying to kill your own session (if it was started long time ago).

    Apparently in vSphere 5. they included a security mechanism integrated to avoid this.

    You can take this by adding a simple test.

    ## max number of idle minutes for sessions to keep$intOlderThan = 60$serviceInstance = Get-View 'ServiceInstance'## get the session manager object$sessMgr = Get-View $serviceInstance.Content.sessionManager## array to hold info about stale sessions$oldSessions = @()foreach ($sess in $sessMgr.SessionList){    if (($sess.LastActiveTime).addminutes($intOlderThan) -lt (Get-Date) -and          $sess.Key -ne $sessMgr.CurrentSession.Key){        $oldSessions += $sess.Key    } ## end if} ## end foreach
    
    ## if there are any old sessions, terminate them; else, just write message to the Warning streamif (($oldSessions | Measure-Object).Count -gt 0) {    ## Terminate sessions than are idle for longer than approved ($intOlderThan)    $sessMgr.TerminateSession($oldSessions)} ## end ifelse {Write-Warning "No sessions that have been idle for more than '$intOlderThan' minutes; no action taken"}
    
  • PowerCLI script to list the df - hl on all ESX hosts?

    Hi Expert,

    I have more than 100 esx host, and I need to list all the df - hl out for my report. Y at - it instead of connect on each esx host to get under output, powercli script that I can use to remove similar information?

    Size of filesystem used Avail use % mounted on

    / dev/sdaa2 20G 1.5 G 17G 8%.

    / dev/CCISS/c0d0p1 1.1 G 118 M 909 M 12% / Boot

    / dev/sdaa6 9.7 G 151 M 9.0 G 2% / Home

    / dev/sdaa7 9.7 G 151 M 9.0 G 2% / tmp

    / dev/sdaa5 9.7 G 317 M 8.9 G 4% / var

    / dev/sdaa8 494M 212 M 257M 46% /vmimages

    Please advice. Thank you

    Are you allowed to enable SSH on servers ESX (i)?

    And are you allowed to establish a SSH session on each ESX (i) Server?

    You have an account and a password on each ESX (i) server that can run the command 'df '?

    If it is Yes, then you can use something like plink.exe in consequence of PuTTY to connect to each ESX (i) server, run the command "df" and retrieve the output.

    There are several available examples to use plink.

    And don't forget that you will need a fingerprint for each server ESX (i) will be stored on the client from which you are running the script.

  • XML and the PowerCLI Scripting Edition

    Good then I am using PowerCLI to do Automation more boring tasks that need to be repeated. But now I'm stuck because I do not understand how to enter commands in the window PowerCLI and creating XML scripts that are called by a manually scheduled task.

    Is there training there or good articles on how to go to the manual entry of orders from command line and in scripts development of really?

    Any information would be greatly appreciated.

    See you soon,.

    Paul

    I assume you are talking about PowerShell scripts and not the XML scripts?

    You can find a good intro to PowerShell scripts in Chapter 10 of free PowerShell ebookTobias.

  • The package PowerCLI script in the Windows executable file / install

    What are the options for packaging / embed PowerCLI script in Windows. EXE file? I would like for several departments to be able to run and collect information from the script without having direct access to the code. This would ensure that the code has been correctly run without modification.

    I know that PowerCLI will be available on these systems, searching for the PowerCLI is not necessary.

    I read that the Primal Script has this ability, but I want a solution that is free and easy to use, if possible.

    If it is not an executable file, maybe even a file coded which makes it difficult for a layman to make changes.

    Thanks in advance for the help!

    I used a similar function of Johan Akerstrom in the past (since I don't have the community installed Extensions).

    See his post Powershell script to generate an executable from a powershell script .

    For this one, I know there is no problem with parameter passing.

    Take this example script

    param(
    [parameter(Mandatory = $true)][string[]]$server)
    
    [void][system.reflection.assembly]::LoadWithPartialName("System.Windows.Forms")
    Add-PSSnapin -Name VMware.VimAutomation.Core
    
    Connect-VIServer -Server $server[windows.forms.messagebox]::Show("Connected to " + $defaultViServer.Name)
    $VM = Get-VM[windows.forms.messagebox]::Show("I counted " + $VM.Count + " guests")
    
    Disconnect-VIServer -Confirm:$false
    

    Note that the script uses Windows Forms to the output data.

    You create the EXE file as follows. I recorded the example script under DoExeTest.ps1

    PS C:\Scripts >.\DoExeTest.ps1 new-PSExecutable
    Script source file: C:\Scripts\DoExeTest.ps1
    Output executable: C:\Scripts\doexetest.exe

    And when you run this, it displays 2 message boxes, one with the name of the vCenter and the other with the number of guests, the script is located in the vCenter.

    C:\Scripts>doexetest.exe 'Site '.

                  

  • I paid creative cloud. I need first. But I had a month of trial version. And now the money from an account has been removed automatically, but I do not have first. What can I do?

    I paid creative cloud. I need first. But I had a month of trial version. And now the money from an account has been removed automatically, but I do not have first. What can I do?

    Sign out of your account of cloud... Restart your computer... Connect to your paid account of cloud

    -If you have more than one email, but of course you use linked to your subscription

    -Connect using http://helpx.adobe.com/x-productkb/policy-pricing/account-password-sign-faq.html

    -https://helpx.adobe.com/creative-cloud/help/sign-in-out-activate-apps.html

    -http://helpx.adobe.com/x-productkb/policy-pricing/activation-network-issues.html

    -https://helpx.adobe.com/x-productkb/policy-pricing/activate-deactivate-products.html

Maybe you are looking for