Using Scripts to Validate Input

by Aug 30, 2010

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!