Search code examples
powershellgetdate

Powershell - including date calulation in export


Team -- trying to expand my powershell script which scans shared drives to include capturing file aging information (see code below). I tried using the TimeSpan function but it returns blank values.

I tried to simplify the script and use Get-Date -- but it also returns no values while all other data elements do contain information.

I also tried creating a variable $DT = Get-Date and including that ... but it also returns blanks.

Any help would be appreciated.


$target_files = Get-ChildItem \\ [source path] \* -recurse -include "*"
$target_files | select-object -Property @{n='Length in MB';e={[math]::Round(($_.Length / 1MB),2)}}, DirectoryName, name, CreationTime, LastWriteTime, New-TimeSpan Get-Date - LastWriteTime |
Export-csv \\ [destination path] \\directoryfiles_Inventory.csv -NoTypeInformation
Import-Csv \\ [destination path] \\directoryfiles_Inventory.csv


Solution

  • I guess you're looking for a Time Difference between now and lastWriteTime date. If that's the case you can do something like this:

    $properties = @(
        @{
            Name = 'Length in MB'
            Expression = {[math]::Round(($_.Length / 1MB),2)}
        }
        'DirectoryName'
        'Name'
        'CreationTime'
        'LastWriteTime'
        @{
            Name = 'Time Difference'
            Expression = {
                ([datetime]::Now - $_.LastWriteTime).TotalHours.ToString('#.# Hours')
            }
        }
    )
    
    Get-ChildItem . | Select-Object $properties | Export-Csv "C:\destination\path\export.csv" -NoTypeInformation
    

    Each item will look like this:

    Length in MB    : 0.04
    DirectoryName   : C:\Users\example.user
    Name            : test.txt
    CreationTime    : 4/27/2021 10:12:57 AM
    LastWriteTime   : 4/27/2021 10:12:57 AM
    Time Difference : 391.8 Hours