How to do it...

Navigate to the location where you created files for lab usage.

  1. Enter the following command:
PS> $FilesWithAge = Get-ChildItem . | Select-Object Name, Length, LastWriteTime
  1. 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) }
  1. 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
  1. Add another property, as an alias to LastWriteTime, called Modified.
PS> $FilesWithAge | Add-Member -MemberType AliasProperty -Name Modified -Value LastWriteTime
  1. To format it like a nice table, use the following:
PS> $FilesWithAge | Format-Table -AutoSize
  1. 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.

  1. Get what object is returned when you run Get-ChildItem.
PS> Get-ChildItem | Get-Member
  1. 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) }
  1. 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
  1. 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
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.77.71