使用 powershell 获取文件的年龄

Get the age of a file using powershell

我有这样的场景,我必须创建一个超过 1 年的文件列表,并根据它的年龄找到年龄,我有这个列表,唯一的问题是获取年龄,当我尝试使用 LastAccessTime 我收到错误消息,因为无法将字符串转换为 system.datetime ,这是我的代码

$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

这是获取年龄的代码

$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
  }

如果您有任何其他解决方案,请告诉我

您需要将字符串转换为 datetime,单独转换在这里不起作用。 ParseExact这里会是你的朋友,第二个参数需要匹配第一个参数的日期格式的输入源。

在此示例中,预计最后访问时间类似于“05-12-2019”,并且 return 一个 datetime 对象。

[datetime]::parseexact($ThisUser.LastAccessTime, 'dd-MM-yy', $null)

OUTPUT: 05 December 2019 00:00:00

来自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

您可以在您的代码中使用这个表达式。我添加了一个 Sort-Object 以方便查看:

$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