Question

Slightly stumped right now and was wondering if the community could give me that quick boost to help me continue with a program I'm working.

At one point in the program that I'm working on, I'm trying to get the 6 newest elements from an array. I want to put the snapshot variable inside of an array in order to get all the snapshots inside of an array. Here's the part of the code that is confusing me at the moment:

$server = "test"
$date = get-date
$tempArray = @()
$snapshot = get-snapshot -VM "test"

foreach ($item in $snapshot){
    $tempArray += $item
}

$tempArray | sort
for ($i = 0; $i -le $tempArray.length-6; $i++){
    remove-item $tempArray[$i]
}

Am I achieving my goal of getting the $snapshot variable inside of my array and is my for loop correctly managing to delete all but the 6 newest?

EDIT: Fixed small issues that hadn't noticed before.

Was it helpful?

Solution

you code has several issues. i am not sure if this will fix your script but these seem to be obvious problems that you should fix first.

foreach ($item in $snapshot){
    $tempArray++ -> this should be $tempArray += $item, right? if you are adding $item to the tempArray
}

$tempArray | sort
for ($i = 0; $i -le $tempArray.length-6; $i++){
    remove-item $snapshot -> this should be remove-item $tempArray[$i], right?
}

OTHER TIPS

Reverse sort by the created timestamp attribute then use the Skip in select object to get everything after the 6 newest

$snapshot = get-snapshot -VM "test"

$snapshot | sort created -descending | select -Skip 6 | Remove-Snapshot -Confirm:$false
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top