Difference between revisions of "Script Extracts and Examples (PowerCLI)"

Jump to navigation Jump to search
→‎Virtual Machine: Added "Enable Change Block Tracking"
(→‎Virtual Machine: Added "Enable Change Block Tracking")
Line 614: Line 614:
     }
     }
}
}
</source>
==== Enable Change Block Tracking ====
This script enables CBT for all VM's managed by the vCentre its run on.  It runs through all VM’s managed by the VC and determines which can be changed, then run through and changes them.
Based on the work by ICT-Freak found at http://ict-freak.nl/2009/12/14/powercli-enable-changed-block-tracking/
<source lang="Powershell">
$log = "VM-EnableCBT.log"
# =====================================================================================================
# Functions...
function Log ($text) {
    [int]$duration = (New-TimeSpan $start (Get-Date)).TotalSeconds
    Write-Host "$duration secs | $text"
}
Function EnableChangeTracking{
    param($vmObj)
    $vmView = Get-View -VIObject $vmObj
   
    Log ($vmObj.Name + " - Reconfiguring VM for CBT...")
    $vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec
    $vmConfigSpec.ChangeTrackingEnabled = $true
    $task = $vmView.ReconfigVM_Task($vmConfigSpec)
    Wait-Task -Task (Get-VIObjectByVIView -MORef $task) -ErrorAction "SilentlyContinue"
    Sleep 1
    Log ($vmObj.Name + " - Creating temp snapshot...")
    $snap = New-Snapshot -Name "Temp snapshot to apply CBT" -VM $vm
   
    Sleep 1
    Log ($vmObj.Name + " - Removing temp snapshot...")
    Remove-Snapshot -Snapshot $snap -Confirm:$false
    Log ($vmObj.Name + " - Completed")
}
# ======================================================================================================
# The actual script...
$start = Get-Date
Start-Transcript -Path $log
Log "Started script run at $start"
$VMsToDo = @()
$VMs = Get-VM | Sort -Property Name
foreach ($vm in $VMs) {
    if (!(($vm.ExtensionData.Config.Extraconfig |?{$_.Key -eq "ctkEnabled"}).Value) -and $vm.Version.ToString() -eq "v7") {
        $VMsToDo += $vm
        Log ($vm.Name + " - Added to ToDo list")
    } else {
        if ((($vm.ExtensionData.Config.Extraconfig |?{$_.Key -eq "ctkEnabled"}).Value)) {
            Log ($vm.Name + " - CBT already enabled")
        } elseif ($vm.Version.ToString() -ne "v7") {
            Log ($vm.Name + " - Not v7, VM hardware version needs to be upgraded !!!")
        }
    }
           
}
Log ("Found " + $VMsToDo.Count + " to enable")
foreach ($vm in $VMsToDo) {
    EnableChangeTracking $vm
}
Log("All completed")
Stop-Transcript
</source>
</source>


Navigation menu