Search code examples
powershellpowershell-3.0powershell-4.0

Get the age of a file using powershell


I have scenario where i have to create a list of files which are older than 1 year and also find the age by how much is it older, i have got the list, only issue is getting the age, when i try to use the LastAccessTime i get error as cannot convert string to system.datetime , here is my code

$time = (Get-Date).AddDays(-365)
$path = "\\fbd-vs1\publicnew"

get-childitem $path -Recurse -File -ErrorAction SilentlyContinue| Where-Object {$_.LastAccessTime - 
lt $time} | select Directory,Name,CreationTime, lastaccesstime , LastWriteTime|
export-csv "D:\AJay\Time\Last.csv" -notypeinfo

Here is the code for getting age

$StartDate=(GET-DATE)
$UserData = "D:\AJay\Time\Last.csv"
$CSVFile = Import-CSV $UserData
Foreach ($ThisUser in $CSVFile)
 {
  //here error as cannot convert string to system.datetime (when i take the value directly it converts to date.)
   $EndDate=[datetime]$ThisUser.LastAccessTime

    $day = NEW-TIMESPAN –Start $StartDate –End $EndDate |select Days

 Select-Object *,@{Name='Age';Expression={$day}} | Export-Csv "D:\AJay\Time\New.csv" -NoTypeInformation
  }

if you have any other solution please let me know


Solution

  • From Select-Object:

    # Create an additional calculated property with the number of Days since the file was last accessed.
    # You can also shorten the key names to be 'l', and 'e', or use Name instead of Label.
    $days = @{l="Days";e={((Get-Date) - $_.LastAccessTime).Days}}
    # You can also shorten the name of your label key to 'l' and your expression key to 'e'.
    Get-ChildItem $PSHOME -File | Select-Object Name, $size, $days
    

    You can use this expression in your code. I've included a Sort-Object to see it easier:

    $days = @{l="Days";e={((Get-Date) - $_.LastAccessTime).Days}}
    get-childitem $path -Recurse -File -ErrorAction SilentlyContinue| Sort-Object -Property LastAccessTime |Where-Object {$_.LastAccessTime -lt $time} | select Directory,Name,CreationTime, lastaccesstime ,$days, LastWriteTime |export-csv "D:\AJay\Time\Last.csv" -notypeinfo