Home > Software design >  Powershell - using SWITCH to categorize file age
Powershell - using SWITCH to categorize file age

Time:04-29

I have an existing script I've written to scan shared drives and create an inventory of all the files within that structure.

One of the fields I capture in my output is 'Age' which is Today - LastWriteTime of the file.

I'd like to include another column in my inventory that categorizes the 'Age' into buckets (0-3.9 Years, 4 - 9.99 Years, and Over 10 Years). I know this can be accomplished via a SWITCH but I can't get anything to work.

Here's the section of the code where I'm capturing the necessary information for each file:

$properties = @(
    @{ Name = 'File Size (MB)'
        Expression = {[math]::Round(($_.Length / 1MB),2)}
    }
    'DirectoryName'
    'Name'
    'CreationTime'
    'LastWriteTime'
    @{ Name = 'Age'
        Expression = {[math]::Round(([datetime]::Now - $_.LastWriteTime).TotalDays /365,2)}
    }
)

I've tried adding a SWITCH statement using the Age calculation, I've tried using Age as a variable and at this point, I feel like I'm just guessing at what the solution could be.

Would someone please assist? Add another column to the output called 'Category' and using the SWITCH to categorize a file based on it's 'Age'.

Thank you in advance for any help, I need a refresh set of eyes.

CodePudding user response:

You can use a filter in this case instead of calculated properties, I believe in this case it should be more efficient, since we need to re-use the value resulting of:

[math]::Round(([datetime]::Now - $_.LastWriteTime).TotalDays /365,2)

The code would look like this:

filter MyFilter {
    $age = [math]::Round(([datetime]::Now - $_.LastWriteTime).TotalDays /365,2)
    $category = switch($age) {
        { 3.99 -ge $_ } { '0-3.9 Years'; break }
        { 9.99 -ge $_ } { '4 - 9.99 Years'; break }
        Default { 'Over 10 Years' }
    }

    [pscustomobject]@{
        'File Size (MB)' = [math]::Round(($_.Length / 1MB), 2)
        'DirectoryName'  = $_.DirectoryName
        'Name'           = $_.Name
        'CreationTime'   = $_.CreationTime
        'LastWriteTime'  = $_.LastWriteTime
        'Age'            = $age
        'Category'       = $category
    }
}

And the usage is rather easy:

Get-ChildItem -Recurse | MyFilter
  • Related