I have a NFS datastore that has VM clones for backup purposes. These VM clones are not in the vCenter inventory. I would like to schedule something that only keeps 7 days worth of clones per VM. Also in this datastore the VM clones are named VMName_Backup_20160830221500, where the last element seems to have been generated using "Get-Date -Format yyyyMMddHHmmss"
I've put together the following, which can produce the list of datastore folders which should be deleted, but I am struggling remove the folders. Below "Remove-Folder $folder -DeletePermanently" is generating "Remove-Folder : Cannot bind parameter 'Folder'. Cannot convert the "VMware.Vim.HostDatastoreBrowserSearchResults" value of type "VMware.Vim.HostDatastoreBrowserSearchResults" to type
"VMware.VimAutomation.ViCore.Types.V1.Inventory.Folder"."
Is there a more elegant way to do this?
I tried this by extracting the clone date from the folder name etc.
$strDatastore = "Host0002_NFS_VMBack"
$CurrentDate = Get-Date -Format yyyyMMddHHmmss
If (-not (Get-PSSnapin VMware.VimAutomation.Core -ErrorAction SilentlyContinue))
{ Try { Add-PSSnapin VMware.VimAutomation.Core -ErrorAction Stop }
Catch { Write-Host "Unable to load PowerCLI, is it installed?" -ForegroundColor Red; Break }
}
Connect-VIServer -Server localhost
$ds = Get-Datastore -Name $strDatastore | % {Get-View $_.Id}
$fileQueryFlags = New-Object VMware.Vim.FileQueryFlags
$fileQueryFlags.FileSize = $true
$fileQueryFlags.FileType = $true
$fileQueryFlags.Modification = $true
$searchSpec = New-Object VMware.Vim.HostDatastoreBrowserSearchSpec
$searchSpec.details = $fileQueryFlags
$searchSpec.matchPattern = "*.vmdk"
$searchSpec.sortFoldersFirst = $true
$dsBrowser = Get-View $ds.browser
$rootPath = "[" + $ds.Name + "]"
$searchResult = $dsBrowser.SearchDatastoreSubFolders($rootPath, $searchSpec)
foreach ($folder in $searchResult)
{
$folpath = $folder.FolderPath
Write-Output $folpath
$CloneDate = $folpath.substring($folpath.length - 11, 2) + "/" + $folpath.substring($folpath.length - 9, 2) + "/" + $folpath.substring($folpath.length - 15, 4)
[datetime]$CloneDateTime = $CloneDate
$DateDiff = (get-date).adddays(-7)
if ($DateDiff -gt $CloneDateTime)
{
Remove-Folder $folder -DeletePermanently
} else {
Write-Output "To be retained as not over 7 days old!"
}
}
Disconnect-VIServer -Confirm:$False
Remove-PSSnapin VMware.VimAutomation.Core