PS PowerCLI-helper-v1.1.ps1

From vwiki
Revision as of 18:16, 21 March 2011 by Sstrutt (talk | contribs) (Initial creation)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search
# ============================================================================
# PowerCLI Helper Functions Library
# ============================================================================
# Simon Strutt        Nov 2010
# ============================================================================
#
# Version 1
# - Initial Creation
#
# Version 1.1 - Nov 2010
# - Get-FolderPath Bugfix: Regex now handles foldernames with "vm" in
# - Get-FolderPath Added : Max iteration depth
#
# TO DO
# - Get-FolderPath limitations
#
# =============================================================================


#=======================================================
# Get-FolderPath ($CurrFolder)
#
# Returns full VM path, given its containing folder ID
#
# Limitations...
# - Doesn't handle ' chars
# - Doesn't handle foldernames with "vm" in
# 
#=======================================================
function Get-FolderPath ($CurrFolder) {
    $path = ""
    $i = 0
    While ($CurrFolder.Name -notmatch "\bvm\b") {
        $path = ($CurrFolder.Name) + "\" + $path
        $CurrFolder = Get-Folder -Id $CurrFolder.ParentId
        $i ++
        if ($i > 15) {
            Log("ERROR: Get-FolderPath ($CurrFolder) exceeded maximum iteration depth")
            $path = "...\" + $path
            break
        }    
    }
    $path
}

#========================================================
# Get-VMDiskUsage($vm2do)
#
# Returns total datastore usage for a VM in GB
#
# Limitations...
# - Doesn't handle Lab Manager VM's well
# 
#=========================================================

function Get-VMDiskUsage($vm2do)
{
    #Initialize variables
    $VMDirs =@()
    $VMSize = 0
 
    $searchSpec = New-Object VMware.Vim.HostDatastoreBrowserSearchSpec
    $searchSpec.details = New-Object VMware.Vim.FileQueryFlags
    $searchSpec.details.fileSize = $TRUE
 
    Get-View -VIObject $vm2do | % {
        #Create an array with the vm's directories
        $VMDirs += $_.Config.Files.VmPathName.split("/")[0]
        $VMDirs += $_.Config.Files.SnapshotDirectory.split("/")[0]
        $VMDirs += $_.Config.Files.SuspendDirectory.split("/")[0]
        $VMDirs += $_.Config.Files.LogDirectory.split("/")[0]
        #Add directories of the vm's virtual disk files
        foreach ($disk in $_.Layout.Disk) {
            foreach ($diskfile in $disk.diskfile){
                $VMDirs += $diskfile.split("/")[0]
            }
        }
        #Only take unique array items
        $VMDirs = $VMDirs | Sort | Get-Unique
 
        foreach ($dir in $VMDirs){
            $ds = Get-Datastore ($dir.split("[")[1]).split("]")[0]
            $dsb = Get-View (($ds | get-view).Browser)
            $taskMoRef  = $dsb.SearchDatastoreSubFolders_Task($dir,$searchSpec)
            $task = Get-View $taskMoRef 
 
            while($task.Info.State -eq "running" -or $task.Info.State -eq "queued"){$task = Get-View $taskMoRef }
            foreach ($result in $task.Info.Result){
                foreach ($file in $result.File){
                    $VMSize += $file.FileSize
                }
            }
        }
    }
 
    # VM disk usage in GB
    $VMSize/1048576000
}


#========================================================
# Get-VMDKDatastores($vm2do)
#
# Returns VMDK datastores and sizes used by a VM (in a hash table)
#
# Limitations...
# - 
# 
#=========================================================

function Get-VMDKDatastores($vm2do)
{
    $VMDKs = Get-VM $vm2do | Get-HardDisk
    $vmdk =@{}
    for ($i=0; $i -le $VMDKs.Length-1; $i++) {
        # Convert path to datasore
        $ds = ([regex]::matches($VMDKs[$i].Filename, "(?<=\[)(.*?)(?=\])")).Item(0).Value
        $ds.Value
        if ($vmdk.ContainsKey($ds)) {
            $vmdk.($ds, $vmdk[$ds] + $VMDKs[$i].CapacityKB)
        } else {
            $vmdk.Add($ds, $VMDKs[$i].CapacityKB)
        }
    }
    $vmdk
}