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

Jump to navigation Jump to search
→‎Script Extracts: Added "VM's with Snapshots Running"
(→‎Getting Started: Added "Scheduling")
(→‎Script Extracts: Added "VM's with Snapshots Running")
Line 441: Line 441:
}
}
Get-VMDiskUsage (Get-VM "MyVM")
Get-VMDiskUsage (Get-VM "MyVM")
</source>
=== VM's with Snapshots Running ===
<source lang="powershell">
$OutputFile = "VM-Snapshot.csv"
function Log ($text) {
    [int]$duration = (New-TimeSpan $start (Get-Date)).TotalSeconds
    Write-Host "$duration secs | $text"
}
function Log-NoNewLine ($text) {
    [int]$duration = (New-TimeSpan $start (Get-Date)).TotalSeconds
    Write-Host "$duration secs | $text" -nonewline
}
$start = Get-Date
$table = New-Object system.Data.DataTable "Results"
$table.columns.add((New-Object system.Data.DataColumn Name,([string])))
$table.columns.add((New-Object system.Data.DataColumn Folder,([string])))
$table.columns.add((New-Object system.Data.DataColumn Snap,([string])))
$table.columns.add((New-Object system.Data.DataColumn Created,([datetime])))
$table.columns.add((New-Object system.Data.DataColumn Size_MB,([single])))
$table.columns.add((New-Object system.Data.DataColumn PowerState,([string])))
Log("Getting list of VMs to check...")
$VMs = Get-VM | Where {$_.PowerState -eq "PoweredOn"} | Sort -Property Name
Log ("Got list of " + ($VMs.Count) + " VMs to check")
$VMno = 0
$VMtot = $VMs.Count
foreach ($vm in $VMs) {
    $VMno = $VMno + 1
    Log-NoNewLine "[$VMno/$VMtot] $vm - "
   
    $Snaps = Get-Snapshot -VM $vm
    if ($Snaps) {
        foreach ($snap in $snaps) {
            $row = $table.NewRow()
            $row.Name = $vm.Name
            $row.Folder = Get-Folder -Id $vm.FolderId
            $row.Snap = $snap.Name
            $row.Created = $snap.Created
            $row.Size_MB = $snap.SizeMB
            $row.PowerState = $snap.PowerState
            Write-Host $row.Snap "| Created" $row.Created "| Size" $row.Size_MB "MB | " $row.PowerState
        }
    } else {
        Write-Host "No snapshot"
    }
}
if ($table.rows.Count) {
    Log "Completed, writing out table..."
   
    $table | Format-Table
    $table | Export-Csv -path $OutputFile
   
    #Send via email
    $smtp = New-Object Net.Mail.SmtpClient -arg "smtpserver"
    $msg = New-Object Net.Mail.MailMessage
    $attach = New-Object Net.Mail.Attachment($OutputFile)
   
    $msg.From = "from"
    $msg.To.Add = "to"
    $msg.Subject = "Snapshots found running!!"
    $msg.Body = "$table.rows.Count snapshots found to be running, see attachment for further info"
   
    $smtp.Send($msg)
    $attach.Dispose()
}
Log "Completed!"
</source>
</source>


Navigation menu