Navigate to the location where you created files for lab usage.
- Enter the following command:
PS> $FilesWithAge = Get-ChildItem . | Select-Object Name, Length, LastWriteTime
- Now, add a property to the variable, $FilesWithAge; the property should be the age of each file, in days.
PS> $FilesWithAge | Add-Member -MemberType ScriptProperty -Name Age -Value { [math]::Round(((Get-Date) - $this.LastWriteTime).TotalDays) }
- Add another property to it, called ComputerName, which is the name of your local host.
PS> $ComputerName = hostname
PS> $FilesWithAge | Add-Member -MemberType NoteProperty -Name ComputerName -Value $ComputerName
- Add another property, as an alias to LastWriteTime, called Modified.
PS> $FilesWithAge | Add-Member -MemberType AliasProperty -Name Modified -Value LastWriteTime
- To format it like a nice table, use the following:
PS> $FilesWithAge | Format-Table -AutoSize
- Now, delete the variable. And query the files within the current directory (because that is what the variable actually held).
PS> Remove-Variable FilesWithAge
PS> Get-ChildItem .
You do not see the Age, the ComputerName or the Modified properties. Try Get-Member if you would like.
Next, we see how to extend the type data itself, so that every time you run Get-ChildItem, you also get the three properties we added to the variable.
- Get what object is returned when you run Get-ChildItem.
PS> Get-ChildItem | Get-Member
- You get System.IO.DirectoryInfo as well as System.IO.FileInfo. We pick System.IO.FileInfo. Run the following commands.
PS> $ComputerName = hostname
PS> Update-TypeData -TypeName System.IO.FileInfo -MemberType NoteProperty -MemberName ComputerName -Value $ComputerName
PS> Update-TypeData -TypeName System.IO.FileInfo -MemberType AliasProperty -MemberName Modified -Value LastWriteTime
PS> Update-TypeData -TypeName System.IO.FileInfo -MemberType ScriptProperty -MemberName Age -Value { [math]::Round(((Get-Date) - $this.LastWriteTime).TotalDays) }
- Query the contents of the current location and optionally, format the output like a table.
PS> Get-ChildItem . | Select-Object Name, Length, ComputerName, Age, Modified | Format-Table -AutoSize
- Do the same for any directory in the file system, the only condition being that the directory should contain at least one file, and not just more directories.
PS> Get-ChildItem ./cities/ | Select-Object Name, Length, ComputerName, Age, Modified | Format-Table -AutoSize