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

Jump to navigation Jump to search
→‎Virtual Machine: Added "Add Attributes to VMs from CSV"
m (→‎Daily ESX Up/Down Check: Added border to script)
(→‎Virtual Machine: Added "Add Attributes to VMs from CSV")
Line 536: Line 536:
Stop-transcript
Stop-transcript
</source>
</source>
=== Add Attributes to VMs from CSV ===
You have the option in vCentre to create your own custom attributes to any of the standard objects.  This can be incredibly useful if you have a sprawling estate of VM's to manage for various different parts of your company, as you can record information like Owning Dept., Product Family etc against your VM's.  The only problem is that you then have fields that have to be manually updated (that and the fact that the info is only held in a VM's vCentre database records, not its VMX, so if you have to re-add a machine to vCentre, you'll lose the custom attributes you populated.
The following script allows you to update VM attributes from a CSV file (which can be very convenient if you've just deployed 20 VM's for a project).
<source lang="Powershell">
<#
=============================================================================================
VM Attribute Updater
=============================================================================================
Simon Strutt  -  March 2010
=============================================================================================
Version 1
- Initial creation!
Version 2
- Added $DontBlank option
=============================================================================================
#>
$start = Get-Date
$CSVinput = "VM-Attribs-ToUpdate.csv"
$Attributes = "Function", "Owner", "RequestID", "Template", "BackupFrequency"      # Custom attributes (fields should already exist in vCentre), should be column headings in CSV
$UserFile = "User.fil"
$PassFile = "Pass.fil"
$DontBlank = 1    # Don't wipe existing populated fields, with blank stuff from spreadsheet
# Include library files
. .\lib\Standard.ps1
Start-Transcript -Path VM-Attrib-Update.log -Append
Log "Started script run at $start"
try {
    $ToUpdate = Import-CSV $CSVinput -errorAction Stop
} catch {
    Log "ERROR: Failed to load CSV Update file($CSVinput)"
    Log $_
    Exit
}
$ToUpdate
# Load password credential from encrypted file
try {
    $pass = Get-Content $PassFile -errorAction Stop | ConvertTo-SecureString
    $user = Get-Content $UserFile -errorAction Stop
    $cred = New-Object System.Management.Automation.PsCredential($user, $pass)
} catch {
    Log "ERROR: Failed to load credentials to use"
    Log $_
    Exit
}
# Disconnect any existing VI Server sessions
if ($DefaultVIServers.Count) {
    Log("Disconnect existing vCentre server connections...")
    Disconnect-VIServer -Server * -Force -Confirm:$false
}
$VCs = $ToUpdate | Select -Property vc -Unique
if (!$VCs.Count) {
    Log ("Found " + $ToUpdate.Count + " VM's to update, accross 1 vCentre")
} else {
    Log ("Found " + $ToUpdate.Count + " VM's to update, accross " + $VCs.Count + " vCentres")
}
foreach ($vc in $VCs) {
    try {
        Log("Connecting to " + $vc.vc)
        $VCconn = Connect-VIServer -Server $vc.vc -Credential $cred -errorAction Stop
    } catch [VMware.VimAutomation.ViCore.Types.V1.ErrorHandling.InvalidLogin] {
        Log("Unable to connect to vCentre, invalid logon error !!")
        Log("Abandoning further script processing in order to prevent potential account lockout.")
        Break
    } catch {
        Log("Unable to connect to vCentre - " + $_)
        Continue
    }
   
    # Check attribute fields exist
    $ExistingAttribs = Get-CustomAttribute -TargetType VirtualMachine
    foreach ($attrib in $Attributes) {
        if (!($ExistingAttribs |?{$_.Name -eq $attrib})) {
            Log("Adding attribute to VC: $attrib")
            New-CustomAttribute -Name $attrib -TargetType VirtualMachine
        }
    }
   
    foreach ($vm in $ToUpdate) {
        if ($vc.vc -ne $vm.vc) {
            Continue
        }
       
        try {
            if ($vm.Folder) {
                $objVM = Get-VM -Location $vm.Folder -Name $vm.vm -errorAction Stop
            } else {
                $objVM = Get-VM -Name $vm.vm -errorAction Stop
            }
        } catch {
            Log ("ERROR: Failed to find VM: " + $vm.vm + " in folder: " + $vm.Folder)
            Continue
        }
       
        if ($objVM.Count -gt 1) {
            Log ("ERROR: Ambiguous VM - found " + $objVM.Count + " possibles for: " + $vm.vm + " in folder: " + $vm.Folder)
            Continue
        }         
       
        $ExistingAnnotats = Get-Annotation -Entity $objVM
        foreach ($attrib in $Attributes) {
            if ($vm.$attrib -eq ($ExistingAnnotats |?{$_.Name -eq $attrib} | Select -ExpandProperty Value)) {
                Log ($vm.vm + " $attrib already set/correct")
                Continue
            }
            if (!$vm.$attrib.Length) {              # CSV field blank
                if ($DontBlank) {                  #  but don't blank
                    Log ($vm.vm + ": $attrib no change")
                } else {
                    Log ($vm.vm + ": $attrib ---> BLANK")
                    Set-Annotation -Entity $objVM -CustomAttribute $attrib -Value $vm.$attrib
                }
            } else {
                Log ($vm.vm + ": $attrib ---> " + $vm.$attrib)
                Set-Annotation -Entity $objVM -CustomAttribute $attrib -Value $vm.$attrib
            }
        }
    }
    Disconnect-VIServer -Server $VCconn -Confirm:$false
}
Stop-Transcript


== ESX ==
== ESX ==

Navigation menu