PowerCLI

 View Only
  • 1.  Need help listing all snapshot and removing them

    Posted Nov 21, 2014 08:21 AM

    Hi Guys,

    I need to list all VM snapshot greater than 2 days old, export it to csv and remove them.

    Here's what I currently got. to list all the VMs with snapshot

    Get-vm | Get-snapshot | Format-Table -Property VM,Name,Created,Description, SizeMB | Export-CSV c:\test\snapshotlist.csv

    however when I add the "Export-CSV c:\test\snapshotlist.csv" all i get is garbage data on the csv file. If i remove it i can see the list of VMs on the cli

    Here's the remove snapshot script.

    $twodaysago = (Get-Date).AddDays(-2)

    Get-Folder miketest | Get-VM | Foreach-Object {

    Get-Snapshot -VM $_ | Foreach-Object {

    if($_.Created -lt $twodaysago) {

    Remove-Snapshot $_ -confirm:$false -runasync

    }}}


    Can someone help me modify this script so it can output all successful snapshot removal on csv and email the status to us?

    Thanks in advance.




  • 2.  RE: Need help listing all snapshot and removing them

    Posted Nov 22, 2014 12:24 PM

    The problem with the first command, is the Format-Output cmdlet call, before exporting it to a csv file. You should only use one of the Format-* cmdlets, to format output going to the screen. In this case, you can use the Select-Object cmdlet, to retrieve only the properties that you want.

    Get-vm | Get-snapshot | Select-Object -Property VM,Name,Created,Description, SizeMB |

    Export-CSV Path c:\test\snapshotlist.csv -NoTypeInformation -UseCulture


    In the second script, you can remove the calls to the Foreach-Object cmdlet, and use the Where-Object cmdlet instead:


    $twodaysago = (Get-Date).AddDays(-2)

    Get-Folder miketest |

    Get-VM |

    Get-Snapshot |

    Where-Object {$_.Created -lt $twodaysago} |

    Remove-Snapshot $_ -confirm:$false -runasync

    You can pipe the output to the Export-CSV cmdlet, like you do in the first command. You can use the Send-MailMessage cmdlet, to send the csv file via e-mail.