Note that there are some explanatory texts on larger screens.

plurals
  1. PODelete oldest versions of a directory in PowerShell
    text
    copied!<p>I have a list of directories which are formatted like version numbers and would like to find the N oldest directories and delete them. For example:</p> <pre><code>/1.2.3.4 /1.2.3.5 /1.2.3.6 </code></pre> <p>I've tried a few things, but I can't quite seem to get where I need to go.</p> <p>My first try was this:</p> <pre><code>ls directory | sort Name | select -first 5 | rm -r </code></pre> <p>However I'm not sure this is going to work in all circumstances, because this will (I presume) do a natural sort. Is that always going to return the correct results?</p> <p>My next thought was that I could use <code>System.Version</code> to do my sorting. So I ended up with this:</p> <pre><code>ls directory | %{[System.Version]$_.Name } | sort | select -first 5 | ??? </code></pre> <p>The problem is that I'm not sure how to tie the directory result to the sorting... What's the best way to do this?</p> <p><code>gci \\directory</code> produces</p> <pre><code>Mode LastWriteTime Length Name ---- ------------- ------ ---- d---- 12/19/2011 5:19 PM 1.0.1052.54849 d---- 12/19/2011 5:29 PM 1.0.1053.54850 d---- 12/19/2011 5:36 PM 1.0.1054.54851 d---- 12/20/2011 2:11 PM 1.0.1056.54875 d---- 12/12/2011 10:39 AM 1.0.991.54625 d---- 12/12/2011 12:08 PM 1.0.992.54627 d---- 12/12/2011 12:22 PM 1.0.993.54628 d---- 12/12/2011 1:15 PM 1.0.994.54630 d---- 12/12/2011 2:45 PM 1.0.996.54636 d---- 12/12/2011 3:34 PM 1.0.997.54640 d---- 12/12/2011 3:48 PM 1.0.998.54641 </code></pre> <p><code>gci \\directory | Sort-Object { $_Name -as [Version] }</code> produces</p> <pre><code>Mode LastWriteTime Length Name ---- ------------- ------ ---- d---- 12/12/2011 1:15 PM 1.0.994.54630 d---- 12/12/2011 12:22 PM 1.0.993.54628 d---- 12/12/2011 2:45 PM 1.0.996.54636 d---- 12/12/2011 3:48 PM 1.0.998.54641 d---- 12/12/2011 3:34 PM 1.0.997.54640 d---- 12/12/2011 12:08 PM 1.0.992.54627 d---- 12/19/2011 5:29 PM 1.0.1053.54850 d---- 12/19/2011 5:19 PM 1.0.1052.54849 d---- 12/19/2011 5:36 PM 1.0.1054.54851 d---- 12/12/2011 10:39 AM 1.0.991.54625 d---- 12/20/2011 2:11 PM 1.0.1056.54875 </code></pre> <p>Does it matter that this is a network share? I'm confused as to why this isn't working... I did a quick sanity check and doing <code>Array.Sort</code> on versions I've created in a unit test are sorted correctly.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload