You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改PowerShell脚本筛选2022年最后编辑文件并导出CSV统计

筛选2022年最后编辑文件的PowerShell脚本修改方案

你之前尝试的{where LastWriteTime -eq 2022}写法错误,因为LastWriteTime是DateTime类型的对象,无法直接和数字2022比较。下面是两种正确的筛选方式,同时优化了原脚本的性能和写法:

方法一:直接判断年份属性

这种写法简单直观,直接提取LastWriteTime的年份进行筛选:

Get-ChildItem 'C:\Users\myusername\Documents\' -Recurse | 
  Where-Object { !$_.PSIsContainer -and $_.LastWriteTime.Year -eq 2022 } | 
  ForEach-Object {
    [PSCustomObject]@{
      Directory     = $_.DirectoryName
      Name          = $_.Name
      Length        = $_.Length
      CreationTime  = $_.CreationTime
      Access        = $_.LastAccessTime
      Owner         = (Get-Acl $_.FullName).Owner
    }
  } | Export-Csv -NoTypeInformation "C:\Users\myusername\Downloads\report.csv"

方法二:用日期范围筛选(更严谨)

如果担心时区、夏令时等因素导致年份判断误差,推荐用明确的日期区间来筛选2022年的文件:

$startOf2022 = Get-Date '2022-01-01'
$startOf2023 = Get-Date '2023-01-01'

Get-ChildItem 'C:\Users\myusername\Documents\' -Recurse | 
  Where-Object { !$_.PSIsContainer -and $_.LastWriteTime -ge $startOf2022 -and $_.LastWriteTime -lt $startOf2023 } | 
  ForEach-Object {
    [PSCustomObject]@{
      Directory     = $_.DirectoryName
      Name          = $_.Name
      Length        = $_.Length
      CreationTime  = $_.CreationTime
      Access        = $_.LastAccessTime
      Owner         = (Get-Acl $_.FullName).Owner
    }
  } | Export-Csv -NoTypeInformation "C:\Users\myusername\Downloads\report.csv"

脚本优化说明

  • 用!$_.PSIsContainer替代$_.PSIsContainer -eq $False,写法更简洁
  • 替换了原脚本中New-Object + Add-Member的繁琐写法,用[PSCustomObject]@{}直接构造对象,更高效直观
  • 去掉了数组累加的操作,直接通过管道将处理结果输出到Export-Csv,避免了大量文件场景下的性能损耗

内容的提问来源于stack exchange,提问作者KD_Raj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 21:35:20