Clone a virtual machine / move to folder / delete VM / as a Powershell Script as a scheduled task ends with "ongoing"

Hi all,.

I would kindly ask your help with a script that needs to run as a scheduled task. It is functional, but does not correct and little need for love at the end...

I want to create a script that

  • find a virtual machine with a pattern on its behalf (realized and works)
  • delete a virtual machine with a reason given in his name (completed works)
  • create a clone of a virtual machine (completed works)
  • move that created clone (upstairs) and move it to a folder named (open)
    or the fact in the clone process

I realized thus far:

Add-pssnapin VMware.VimAutomation.Core
# Import CSV backup
$backupinfo = import-Csv C:\scripts\vm_backup\test.csv
VCenter servername #Set
$vcenter_server = "name servers".
#Connect to vCenter
SE connect-VIServer $vcenter_Server

# BEGIN OLD BACKUP CLEANUP
#Select all old backups
$old_backups = get - VM *-backups
{if ($old_backups)}
{foreach ($backup_vm to $old_backups)
Get - VM $backup_vm | Remove-VM - DeleteFromDisk-confirm: $false
}
}

# START QUEUING NEW CLONES
#Increment through CSV
{foreach ($customer to $backupinfo)
$target_host is get-VMHost-name $customer. TargetHost
If {($target_host)
Date format #Set for clone names
$date = get-Date-Format 'YYYY-MM-dd ".
Date format #Set for emails
$time = (get-Date - f "Hh: mm")
#Get SourceVM
$vm is get - VM $customer. SourceVM
# Create new snapshot clone
$cloneSnap = $vm | New-Snapshot - name "instant Clone.
# Get the managed object display
$vmView = $vm | Get-View
# Get the managed folder object reference
$cloneFolder = $vmView.parent
# Construction specification clone
$cloneSpec = new-object Vmware.Vim.VirtualMachineCloneSpec
# Make linked disc specification?
$cloneSpec.Snapshot = $vmView.Snapshot.CurrentSnapshot
#Set VirtualMachineRelocateSpec
$cloneSpec.Location = new-object Vmware.Vim.VirtualMachineRelocateSpec
#Thin commissioning
$cloneSpec.Location.Transform = [Vmware.Vim.VirtualMachineRelocateTransformation]: sparse
#Target data store
$cloneSpec.Location.Datastore = (get-Datastore-name $customer. TargetDS | Get - View). MoRef
#Target host
$cloneSpec.Location.Host = (get-VMHost-name $customer. TargetHost | Get - View). MoRef
#Target list of resources, from the first VM in the TargetHost
$cloneSpec.Location.Pool = (get-VMHost-name $customer. TargetHost | Get - VM | Select-Object - 1 first | Get - View). ResourcePool
Name of clone #Set
$cloneName = ' date of $vm-$- $temps - backup ".
# Create clone
$clone_task = $vmView.CloneVM_Task ($cloneFolder, $cloneName, $cloneSpec)
# Remove snapshot created for clone, will automatically queues
Get-Snapshot - VM (VM-Get-name $customer. SourceVM) - name $cloneSnap | Remove-Snapshot - confirm: $False
}
}

# Move folder in VM Clone
Move-VM - VM * - backups - Destination Clone

VCentre #Disconnect
Disconnect-VIServer-confirm: $false

The script itself runs so far and does what it should, but the scheduled task is always "in process of execution". Now, I created a work around in this way, I have finished the task after two hours of running; but there must be a better solution that works properly.
As well as the part with the rise of the virtual machine.

Could you maybe help me or have a good idea how to solve this problem?

Thanks in advance

Try again with

PowerShell-no interactive - noprofile - executionpolicy override - file C:\scripts\scriptname.ps1

Tags: VMware

Similar Questions

  • I want to move virtual machines to a folder called Linux name, but we have several file of the same name in our Datacenter, please give me PowerCLI Script to move exactly

    I want to move virtual machines to a folder called Linux name, but we have several file of the same name in our Datacenter, please give me PowerCLI Script to move exactly.

    I tried to use for the function FolderByPath below, but don't know how to use it and have worked. Please help me in this.

    Function Get-FolderByPath {}

    < #.

    . Records of recovery SYNOPSIS by giving a path

    . DESCRIPTION the function will retrieve a record by its

    path. The path can contain any type of leave (folder or)

    Data Center).

    . Author NOTES: Luc relaxing

    . Path PARAMETER

    The path to the folder.

    This is a required parameter.

    . Path PARAMETER

    The path to the folder.

    This is a required parameter.

    . PARAMETER separator

    The character used to separate the leaves in the

    path. The default value is ' / '.

    . EXAMPLE OF

    PS > Get-FolderByPath-path ' Datacenter/Folder1/Folder2 ".

    . EXAMPLE OF

    PS > Get-FolderByPath-path "Folder1 > Folder2"-separator ' > '

    # >

    (param

    [CmdletBinding()]

    [parameter (Mandatory = $true)]

    [System.String []] ${Path}.

    [tank] ${delimiter} = ' / '.

    )

    {in process

    If (((Get-PowerCLIConfiguration).)) DefaultVIServerMode - eq "Multiple") {}

    $vcs = $defaultVIServers

    }

    else {}

    $vcs = $defaultVIServers [0]

    }

    {foreach ($vc to $vcs)

    {foreach ($strPath in $Path)

    $root = get-file-name of the server data $vc centers

    $strPath.Split ($Separator) | %{

    $root = get-inventory-name $_-location $root - server $vc - NoRecursion

    If ((Get-stocks-localisation $root-NoRecursion |)) Select--ExpandProperty name)-contains "vm") {}

    $root = get-inventory-name "vm" - location $root - server $vc - NoRecursion

    }

    }

    $root | where {$_-is [VMware.VimAutomation.ViCore.Impl.V1.Inventory.FolderImpl]}|% {}}

    Get-file-name $_. Name - location $root. Parent - Server $vc

    }

    }

    }

    }

    }

    You can try to retrieve the object file by steps as well.

    Something like this for example

    $folder = get-data center-name 'LTX01-G8 | Get-file-name "LTX-servers | Get-file-name "LTX servers 0000 - 0299. Get-file-name Linux

    I guess the first qualification in your path was the data center.

  • Clone the virtual machine to the local data store

    Hi all

    I'm looking to automate a task daily (or almost) of my friends with a small script with powercli.

    I'm trying to "backup" or to clone a virtual machine, I work in a storage of one of our servers.

    The servers are managed by a 5.1 vCenter and the machine is on a shared storage.

    From time to time, I clean, stop the machine, remove all snapshots and clone the virtual machine to one of the local server as a backup storage. So I put together a small script which almost works. It works as long as the target data store is a shared storage, but not with a local storage.

    I get always an error that claims it can not access the local data store and is not a permissions problem...

    Given that I can accomplish this via the customer without problem I thought it is possible via powercli too, or I'm wrong?

    My Script up to now:

    # Variables
    $VC = "vc.domain.com" #vCenter Server
    $User = "domain\user" #User
    $Pass = 'test123' #User PW
    $VMName = 'scripttest' #VM
    $BackupSuffix = "backup" #Suffix to add the name of VM to mark this as a backup
    $VmHost = "esx2.domain.com".
    $Datastore = 'ESX2-LocalData' #Datastore
    $BackupFolder = 'Backup' #Folder the VM gets classified


    # Register cmdlets to VMware

    If (-not (Get-PSSnapin VMware.VimAutomation.Core - ErrorAction SilentlyContinue)) {}

    Add-PSSnapin VMware.VimAutomation.Core

    }


    # Connect to the server

    SE connect-ViServer $VC - user $User-password $Pass


    # Remove the old clone

    $OldBackups = get - VM | WHERE {$_.} {Name: corresponds to '$VMName - $BackupSuffix'}

    If ($OldBackups - don't "")

    {

    If ($OldBackups.Count - gt 1)

    {

    Write-Host "better check! "Found several results:

    Foreach ($VM to $OldBackups)

    {

    Write-Host $VM. Name

    }

    }

    on the other

    {

    Remove-VM - VM $OldBackups - DeleteFromDisk-confirm: $false

    }

    }


    # Clone VM

    $VMInfo = get - VM $VMName | Get-View

    $CloneSpec = new-Object Vmware.Vim.VirtualMachineCloneSpec

    $CloneSpec.Snapshot = $VMInfo.Snapshot.CurrentSnaphshot

    $CloneSpec.Location = new-Object Vmware.Vim.VirtualMachineRelocateSpec

    $CloneSpec.Location.Datastore = (get-Datastore-name $Datastore |) Get - View). MoRef

    $CloneSpec.Location.Transform = [Vmware.Vim.VirtualMachineRelocateTransformation]: sparse

    $CloneFolder = $VMInfo.Parent

    $CloneName = "$VMName - $BackupSuffix".

    $TaskCloneID = $VMInfo.CloneVM_Task ($CloneFolder, $CloneName, $CloneSpec)


    # Check if the task is completed


    $Check = $false

    While ($Check - eq $false)

    {

    $Tasks = get-job | Select State, id | Where {$_.} State - eq "Running" - and $_. State - eq "pending"}

    ForEach ($Task in $Tasks)

    {

    If ($Task.id - eq $TaskCloneID)

    {$Check = $false}

    on the other

    {$Check = $true}

    }

    Start-Sleep 10

    }

    # Move clone to the backup folder

    Move-VM - VM '$VMName - $BackupSuffix' - Destination $BackupFolder


    # Disconnect

    Disconnect-VIServer-confirm: $false

    Can you show us the complete error message you get?

    BTW, the clone step can be replaced by the New-VM cmdlet with the setting of the virtual machine.

  • VCo workflow to clone a virtual machine of centos. Network interface problem

    Hello

    I use vco workflows to clone a virtual machine of vcenter. The virtual machine is running centos 6.0. When cloning is complete. I see the network eth0 and eth1 interfaces set correctly the static gateway ip and address information I provided. I deleted the 70 - persistent - net .rules on the basic vm form which I clone. So, I get the correct interface names. But when vm powers on and I run "ifconfig eth0" I don't see the IP address of this interface has all the details.  same for the other interface also.

    But if I do a system restart network without changes to networking and then do an ifconfig I see the IP with the previous information.   I don't know why the service network restart is necessary so that he can recognize the ip address.

    Any ideas what I could do wrong. or to avoid this manual step of the execution of the service network restart command on the creation of the vm.

    Thank you

    Kiran

    Yes I'm restarting after after the application of customization.

    Has been able to solve the problem... In CentOS, the network service does not work by default. This is why it does not have network interfaces at startup. So now the machine instant, I started the network services and stop the Network Manager service

    using chkconfig network on

    chkconfig NetworkManager off

    and then cloned from this virtual machine... and apply the customization settings. during the start now it shows the interfaces properly without needing a service restart

  • Error trying to clone a virtual machine

    Hello

    I'm trying to use the vsphere api 5.0 to clone a virtual machine that was created in the web client.

    Here is my XML SOAP message:

    <? XML version = "1.0" encoding = "UTF-8"? >

    " < SOAP-SOAP ENV:Envelope - ENV:encodingStyle = ' http://schemas.xmlsoap.org/SOAP/encoding/ "xmlns:SOAP - ENV =" " http://schemas.xmlsoap.org/SOAP/envelope/ "container =" " http://www.w3.org/2001/XMLSchema "" xmlns: xsi = " " http://www.w3.org/2001/XMLSchema-instance "xmlns:SOAP - ENC =" " http://schemas.xmlsoap.org/SOAP/encoding/ ">

    < SOAP - ENV:Body >

    < CloneVM_Task xmlns = "urn: vim25" >

    < _this type = 'VirtualMachine' > vm-xxxxx < / _this >

    < folder > datacenter-xxxxx < / case >

    < name > clone-test-1 < / name >

    < spec >

    < location >

    store of data <>data store - xxxxx < / datastore >

    resgroup-xxxxx < pool > < / pool >

    < / location >

    false < template > < / template >

    false < powerOn > < / powerOn >

    < / spec >

    < / CloneVM_Task >

    < / SOAP - ENV:Body >

    < / SOAP - ENV:Envelope >

    but I get the error "the application refers to an unexpected or unknown type".

    Here is the entire response in a table:

    {Array (15)}

    'key' = >

    String(11) "task-xxxxxxx".

    "task" = >

    String(11) "task-xxxxxxx".

    'name' = >

    (12) a string "CloneVM_Task".

    'descriptionId' = >

    (20) a string "VirtualMachine.clone".

    'entity' = >

    String (8) "vm-xxxxx".

    "entityName" = >

    (8) a string 'xxxxxx '.

    'State' = >

    String(5) "error".

    'cancelled' = >

    String(5) "false."

    'Cancel' = >

    (4) a string 'true '.

    'error' = >

    {Array (2)}

    'fault' = >

    {Array (1)}

    "argument" = >

    (22) a string "ManagedObjectReference".

    }

    'localizedMessage' = >

    String (52) "request refers to an unexpected or unknown type."

    }

    'reason' = >

    {Array (1)}

    'userName' = >

    String (10) "myusername".

    }

    'queueTime' = >

    (26) string "xxxx".

    "startTime" = >

    (27) string "xxxx".

    'completeTime' = >

    (26) string "xxxx".

    'eventChainId' = >

    String (7) 'xxxxxxx '.

    }

    Thanks in advance for any help, it will be greatly appreciated!

    Yes, login and vcenter.

    Thanks for trying to help, but I managed to solve it.  It turns out that it was

    1. I was providing the setting wrong folder (should have been the result of FindByInventoryPath('your_data_center_name/vm') instead of FindByInventoryPath ('your_data_center_name')

    2. I didn't need to provide anything inside the 'location' parameter, it comes to be present

    Thank you again and hope that the above comments help someone else trying to do the same thing

  • Clone a virtual machine to a Cluster data store

    Hello

    Really simple (hopefully), but I'm trying to write a workflow that includes the provision of a virtual computer to a cluster of data store. I'm a link to the workflow 'Clone the virtual machine, no customizations' that only accepts a store of input data.

    I hope that I am a bit stupid here and there is a simple answer?

    Thank you.

    There is no simple answer.  DRS clusters are actually a set of rules and not a real thing, you can deploy a VMDK.  I suggest to use Onyx to deploy a virtual computer to a DRS cluster and see what it generates.  If I remember correctly, it executes DRS rules to get a recommendation for where to put a VMDK fundamentally and then uses the exit in order to actually deploy the model.

    I opted to write just a simple workflow that finds the data store with the most of freespace that corresponds to a string - for example, if I have a DRS cluster named DSCluster_ugabuga, I have a lot of data stores named something like "ugabuga... ».  So you ask these storages of data and find the one which most freespace.

  • Clone a virtual machine directly from single ESXi host

    Hi, I want to clone a virtual machine with all the related feathers which the Associate ID (CPU ID, UUID, BIOS ID, etc.) and redeployed on another single ESXi host. It could help me how can I do?

    Hello

    without vCenter server you can accomplish this by check script PowerCLI this useful post below:

    Tools of HL - part 1 - clone a virtual machine without vCenter - notes LucD

    If you want to clone individual disks check this KB:

    VMware KB: Cloning of disks to the individual virtual machine through the ESX/ESXi terminal host

    _________________________________________________________________________________________

    If you have found this device or any other answer useful, please consider to award points. (use the useful or correct)

    Kind regards

    P.

  • Clone a virtual machine and change is the network settings?

    I'm looking to clone a virtual machine several times change the network connection and the IP he uses, any help appreciated.

    NP, alternative, will host this script:

    $vmlist=Import-CSVC:vms.csv
    foreach($itemin$vmlist) {
     # I like to map out my variables
     $vmname=$item.vmname
     $ipaddr=$item.ipaddress
     $subnet=$item.subnet
     $gateway=$item.gateway
     $pdnswins=$item.pdnswins
     $sdnswins=$item.sdnswins
     #Get the current interface info
     $GuestInterface= Get-VMGuestNetworkInterface -VM $vmname -HostCredential $HostCred-GuestCredential$GuestCred
     #If the IP in the VM matches, then I don't need to update
     If ($ipaddr-ne$($GuestInterface.ip)) {
         Set-VMGuestNetworkInterface-VMGuestNetworkInterface$GuestInterface -HostCredential $HostCred -GuestCredential $GuestCred -IP $ipaddr -Netmask $subnet -Gateway $gateway -DNS $pdnswins,$sdnswins-WINS  $pdnswins,$sdnswins
     }
    }
  • How to clone a virtual machine using ESXi 4.1 and vSphere?

    Instructions for I have seen that you can click with the right button on a virtual machine and choose "Clone", but I think it's only for vCenter

    Is there a way to clone a virtual machine in vSphere?

    Thank you

    If you have a licensed copy of ESXi (not vSphere Hypervisor, the free version), you can try the document below.  However, if you do not have a licensed copy you vCenter for cloning function

    http://communities.VMware.com/docs/doc-11708

  • How to clone a virtual machine with the drive?

    Hello

    Previously, I used VMware Workstation and has a mastery of "clone". Now I use the reader and I would like to clone my current VM and there is no special orders. Simply copy the directory would probably not there a lot of information such as DNS name, etc. that are likely to be changed. Is it possible to clone a virtual machine with player or do I Workstation?

    Many thanks in advance,

    Nicolas

    In my computer a full clone is nothing more then is not a copy that was made unique in the process and the players of VMware capacity but there is nothing stopping you from manually making a copy and then manually by making the changes to make it unique.

  • How is it possible to clone a virtual machine cluster when data warehouses not presented in source and destination

    I did not know that on ESX 3.5, in order to afin de vivre live clone a virtual machine from one ESX host to another, source and destination stores had to be available. However, I'm currently cloning a virtual machine to a host in a datacenter and cluster to one host in a different data center, but the destination store is not available at the source host and visa versa.

    How is that possible?  This is a new feature of vSphere?

    That seems to work on the console port. See this thread: http://communities.vmware.com/message/1475721#1475721

    AWo

    VCP 3 & 4

    Author @ vmwire.net

    \[:o]===\[o:]

    = You want to have this ad as a ringtone on your mobile phone? =

    = Send 'Assignment' to 911 for only $999999,99! =

  • script to remove all the virtual machines in a folder or a group resource

    Someone at - it a script that will find all the virtual machines within a file or a group of resources and then delete the virtual machines?

    If you're dealing with a specific resource pool or a folder, you can use these.

    $vmlist = get-folder -name "TEST2"  | get-vm
    $vmlist = get-resourcepool -name TestServers | get-vm
    

    And then send it to something like this

    $vmlist | ForEach {
         If ($_.PowerState  -eq "PoweredOn")
              {
              Stop-VM -VM $_.Name -Confirm:$False
              }
         Remove-VM -VM $_.Name -Confirm:$False      }
    

    Also to find files of type VM

    get-folder -name | where {$_.IsChildTypeVM -eq "True"}
    

    Do you need to search the children files or resource pools as well?

    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.

  • Clone the virtual machine between two ESX 3.5.0 servers (low connection)

    Hi all!

    I have two ESX 3.5.0 servers that are managed by a vCenter servers one have just the connection of 32 KB.

    I need to clone one of my virtual machines from one to the other ESX is W2k8 created with 40 GB HARD drive. I tried to start it clone trough my low connection, but the task is about 86% for 4 days :|

    Is it possible to clone virtualmachine on one of my ESX for its local storage and after that, get it by vCenter for example an external HARD drive and then copy them all to my second ESX? How to run copied virtual machine on my second ESX? Maybe I can do it with another way - ideas?

    Two ESX are the same versions and machines, only the names and the ip addresses are different.

    Thanks for the tips

    Kris

    I don't think it is possible since the virtual disk will be 40 GB in size - I was suggesting using a laptop as a server NFS ESX sees and access the virtual machine for this storage clone - it take the first vessel of ESX host it to secondary site attach NFS datastore on the second ESX Server and using the browser of data store you navigate to the cloned VMX of VM file and to him the second ESX host - you can cold migrate leaving the second host and then move the cursor above for the storage you want.

    If you find this or any other answer useful please consider awarding points marking the answer correct or useful

  • Recompose a list of clone bound virtual machines within a pool using view server connection

    Hi all

    I use View with ESXi 4.1 4.6, composer is 2.6. Yesterday, I recomposed 8 pools from the mine to the snapshot of the updated gold statue.

    I have 140 VM in each pool. I checked today and about 125 to 130 of the virtual machine in each pool has been recomposed the new image, but 10-15 VMS in each pool were not reconstructed. They are currently closed. If I manually turn the, they have the old image.

    Now, I want to select just 10-15 VMS thos s in each pool and recompose the. The only options that I can see is to recompose the whole new pool or redial each VM one by one. I don't want to recompose the whole pool again and recomposing each VM individually will take a LONG time.

    When I go to desktop computers discovered in the administrator of the display and select the VM not recomposed, I don't get the opportunity to recompose.

    Can someone please help.

    There were errors, but I was unable to see them and all I could see the gray blocks, but nothing written on them. It seemed that the error windows were suspended by themselves.

    Thank you

    -Jay

    You can select certainly several computers desktop to a redial.  If your sub screen of the inventory of the pool just highlight several desktop computers and select recompose.  You can even choose the View Composer details view to sort by the image that is currently loaded.

    If you have problems for a reason, you could look at deleting workstations provided that they are in a floating pool that would simply allow view the based on the default image assigned to the pool to recreate.

  • Get-file provides an account of all virtual machines in the folder structure.

    Hi all

    Tried a few searches in the community, but impossible to find exactly what I was looking for.  We have a configuration folder structure in vCenter.  We have some companies that we bought over time and we set up a folder, separate them with a top-level folder and folders nested for different types of virtual machine below, something like:

    CompanyX

    -Mail servers

    -Web servers

    -DB servers

    For the purposes of internal billing, asked me to get a count of all virtual machines for each company.  I can get the count for virtual machines directly in the "CompanyX" folder, but it does not include virtual machines in subfolders.  This is the script I used so far:

    Write-Output "VM enumeration for CompanyX VMware environment Total: $((Get-dossier 'CompanyX' |)). "(Get-VM) .count) | out-file "D:\ScriptResults\CompanyX.txt" - append

    As I said, that works very well for the virtual machines in the head in the parent folder, but it does not go down to the next layer.  Is there a way to get folder do that?

    I am a novice PowerShell/PowerCLI, so forgive me if I'm missing something obvious.

    Thank you

    Bob

    Hi Bob,

    I don't know if it was different in previous versions, but in the latest PowerCLI version 4.1 U1 if you

    Get-file "CompanyX" | Get - VM

    It will retrieve the VM in the top folder and all subfolders. You can easily check this with:

    Get-file "CompanyX" | Get - VM | Select-Object - Property Name, folder

    If you only want the virtual machine in the top folder you can use:

    Get-file "CompanyX" - NoRecursion. Get - VM

    The following script will get the VM number for all companies and write the result to a .csv file.

    $ExcludeFolders = "Discovered virtual machine","other folder to exclude"
    Get-Folder vm | Get-Folder -NoRecursion | `
    Where-Object {$ExcludeFolders -notcontains $_.Name } | `
    ForEach-Object {
      $Folder = $_
      $Report = "" | Select-Object -Property Company,"Number of VM's"
      $Report.Company = $Folder.Name
      $Report."Number of VM's" = ($Folder | Get-VM | Measure-Object).Count
      $Report
    } | Export-Csv -Path CompanyVMsCount.csv -NoTypeInformation -UseCulture 
    

    If there is high records of the page you want to exclude from the list you can add them to the $ExcludeFolders variable in the first line of the script. The second line of the script gets all the 'vm' top of the folders page. The third line filter unwanted records. A few lines create the output objects. And the last line written objects in a .csv file.

    I added the Measure-Object cmdlet for the ($Folder |) Get - VM | Measure - Object). Account because otherwise you will get an error if the number is 0 or 1.

    Best regards, Robert

Maybe you are looking for