Thursday, March 12, 2009

Finding folders with specific dates old using the name.

Hi,
Recently, I had to do a script that finds all folders in a directory who have a certain number of days, each folder has a date, with format YYYYMMDD, and I had to find all folders that were X numbers of days old to move it to another folder.

After spending some time figuring out how can I could that, I will share with you the main function that I used and that is working right now.

The most tricky part was to validate that the folder was a valid date.
Well this is how I did it:

$dtout=New-Object datetime
$GciFiles = get-childitem $Path | where-object { $_.PsIsContainer -and $_.Name -match '^20[0-9][0-9][0-1][0-9][0-3][0-9]$' -and ([datetime]::tryParseExact($_.Name,"yyyyMMdd",[System.Globalization.CultureInfo]::EnglishName,[System.Globalization.DateTimeStyles]::None,[ref]$dtOut)) } | Where-Object { ((get-date) - [datetime]::parseexact($_.Name,"yyyyMMdd",$null)).days -ge $days } | Select-Object name


First, I declared a variable named dtout, so I could use it later, then I use the variable GciFiles to store the return of the gci(I know I could do that in a single line, but I wanted that way):

$GciFiles = get-childitem $Path

Then, the result of the gci, I filter only the folders and the folders whose name had the correct format, and using the function tryParseExact, I can validate that the date.

$GciFiles = get-childitem $Path | where-object { $_.PsIsContainer -and $_.Name -match '^20[0-9][0-9][0-1][0-9][0-3][0-9]$' -and ([datetime]::tryParseExact($_.Name,"yyyyMMdd",[System.Globalization.CultureInfo]::EnglishName,[System.Globalization.DateTimeStyles]::None,[ref]$dtOut)) }

Then, after I validated the date and the date was valid, I obtain the number of days from the folder's day to today and if that number is greater or equal the $days parameter the name is selected:

$GciFiles = get-childitem $Path | where-object { $_.PsIsContainer -and $_.Name -match '^20[0-9][0-9][0-1][0-9][0-3][0-9]$' -and ([datetime]::tryParseExact($_.Name,"yyyyMMdd",[System.Globalization.CultureInfo]::EnglishName,[System.Globalization.DateTimeStyles]::None,[ref]$dtOut)) } | Where-Object { ((get-date) - [datetime]::parseexact($_.Name,"yyyyMMdd",$null)).days -ge $days } | Select-Object name

No comments: