Creating Great Reports

by Jul 14, 2014

All PowerShell versions

You can change all properties of objects when you clone them. Cloning objects can be done to “detach” the object data from the underlying real object and is a great idea. Once you cloned objects, you can do whatever you want with the object, for example, change or adjust its properties.

To clone objects, run them through Select-Object. That is all.

This example takes a folder listing, runs it through Select-Object, and then prettifies some of the data:

Get-ChildItem -Path c:\windows |
  # clone the objects and keep the properties you want/add new properties (like "age...")
  Select-Object -Property LastWriteTime, 'Age(days)', Length, Name, PSIsContainer |
  # change the properties of the cloned object as you like
  ForEach-Object {
    # calculate the file/folder age in days
    $_.'Age(days)' = (New-Timespan -Start $_.LastWriteTime).Days

    # if it is a file, change size in bytes to size in MB
    if ($_.PSisContainer -eq $false)
    {
      $_.Length = ('{0:N1} MB' -f ($_.Length / 1MB))
    }

    # do not forget to return the adjusted object so the next one gets it
    $_
  } |
  # finally, select the properties you want in your report:
  Select-Object -Property LastWriteTime, 'Age(days)', Length, Name |
  # sort them as you like:
  Sort-Object -Property LastWriteTime -Descending |
  Out-GridView 

The result shows file size in MB rather than bytes, and a new column called “Age(days)” with the file and folder age in days.

Twitter This Tip! ReTweet this Tip!