I only recently started using PowerShell and was amazed with the flexibility and ease of use. Here’s a sample script I put together after a few hours of playing around. I have also described the scenario around the requirement for this script.
Task at hand: A folder contains many files such as:
- File1v1
- File2v1
- File2v2
- ABCv3
- ABCv4
- ABCv5
- MyFile9
- MyFile15
- MyFile21
The requirement was to keep only the latest version of each file (and therefore identify the older files to move). In my case, I have over 400 such files at any given time (and the number will grow.) The only way to distinguish (in my specific case) which file was the ‘latest’ was to use the numeric suffix at the end of each file (timestamps etc. are not reliable for my requirement.)
So to automate this task, I figured I’d try to learn PowerShell and put it to use. Here is the script I used:
################# IdentifyOlderVersions.ps1 ######################
$files = dir X:myFolder*.* | Sort-Object
$prevfile = “”
$filenamewithoutsuffix = “”
$previousversions = @()
foreach ($file in $files)
{
$filenamewithoutsuffix = ($file.BaseName -split “d+$”)[0]
if ($filenamewithoutsuffix -eq $prevfile)
{
# this is the same file ‘lineage’, add the current file to the array
$previousversions = $previousversions + $file
}
else
{
# new lineage, need to move files and then reset $previousversions
$listoffilestobemoved = “”
$tmpindex = 0
foreach ($filetobemoved in $previousversions)
{
# The check below is to ensure that we only list the files to be moved
if ($tmpindex -eq ($previousversions.length – 1))
{
break
}
$listoffilestobemoved = $listoffilestobemoved + “,” + $filetobemoved
$tmpindex++
}
$previousversions = @()
$previousversions = $previousversions + $file
if ($listoffilestobemoved -ne “”)
{
Write-Host $listoffilestobemoved
}
}
# in both cases, assign the previous filename = current one
$prevfile = $filenamewithoutsuffix
}
################# IdentifyOlderVersions.ps1 ######################
This worked as a charm, and as you can see, some pretty involved scripts can be put together. We can also create .NET classes inside a script, and use those to achieve more than what is normally possible.
I encourage you to try using PowerShell for all such tedious tasks. There are some great hints and information (including link to a free course book) at http://www.microsoft.com/technet/scriptcenter/topics/winpsh/toolbox.mspx. The starting point for most of us should be http://www.microsoft.com/technet/scriptcenter/topics/winpsh/pshell2.mspx. Get the CTP2 latest release and start playing around!