Using Scripts to Validate Input

For tricky validation checks, you should use arbitrary PowerShell code to validate. The function Copy-OldFiles will only accept files (no folders) and those that are older (in days) than specified in -Days:

function Copy-OldFiles {
param(
$Days=30,
[Parameter(ValueFromPipeline=$true)]
[System.IO.FileInfo]
[ValidateScript({ (New-TimeSpan $_.LastWriteTime).Days -gt $Days })]
$FileObject
)

process {
"Archiving file {0} (Age {1})..." -f $FileObject.FullName, (New-TimeSpan $_.LastWriteTime).Days
}
}

The validation script will then check whether the file submitted via the pipeline is older than specified in -Days. If not, the file is rejected. And this is how you could archive all log files in your Windows folder that are older than 40 days:

dir $env:windir -Filter *.log | Copy-OldFiles -Days 40 -ErrorAction SilentlyContinue

Twitter This Tip! ReTweet this Tip!


Posted Aug 30 2010, 08:00 AM by ps1
Concentrated Tech NSoftware Dell Compellent Sponsored by Idera and Concentrated Tech and NSoftware and Dell Compellent
Copyright 2011 PowerShell.com. All rights reserved.