You need to enable JavaScript to run this app. PowerShell实现按时间跨度筛选子目录文件并输出单结果表
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell实现按时间跨度筛选子目录文件并输出单结果表

问题根因说明

代码存在三处核心逻辑错误,直接导致了筛选失效、结果分散的现象:

  • 管道符衔接缺失:PowerShell 中跨换行执行管道命令时,必须在换行前或者下一行开头显式写入管道符 |。初始代码在 Get-ChildItem 命令换行后直接写 Where-Object,会被解析为两个独立的单行命令:Get-ChildItem 拿到目录内容后直接触发控制台逐目录输出表格,后续的时间筛选逻辑根本没有接入数据流,自然不会生效。
  • 输出逻辑顺序错误:筛选后直接调用 Format-Table 属于输出终结命令,会把管道中的对象直接转成固定格式的表格文本,既无法后续汇总,也会因为逐目录遍历的触发节奏,导致每个子目录单独渲染一张表。
  • 遍历范围过宽:Get-ChildItem 默认会同时返回文件和目录对象,混在结果中会干扰筛选判断。
可直接运行的修正方案

基础功能版本

完全覆盖核心需求:全子目录递归遍历、严格时间范围筛选、排除目录条目、汇总为单张对象表,包含文件名、文件大小、最后修改时间三类核心字段:

$timestartstr = "2020-09-16 07:00:00"
$timestart = [datetime]::ParseExact($timestartstr, "yyyy-MM-dd HH:mm:ss", $null)
$timeendstr = "2020-09-16 09:00:00"
$timeend = [datetime]::ParseExact($timeendstr, "yyyy-MM-dd HH:mm:ss", $null)

$dir = "path\to\parent\folder"

Get-ChildItem -Recurse -File $dir |
    Where-Object {$_.LastWriteTime -gt $timestart -and $_.LastWriteTime -lt $timeend} |
        Select-Object Name,LastWriteTime,Length

可读性优化版本

在基础版逻辑上,把原始字节长度换算为保留两位小数的MB值,避免出现一长串数字难以辨认的问题:

$timestartstr = "2020-09-16 07:00:00"
$timestart = [datetime]::ParseExact($timestartstr, "yyyy-MM-dd HH:mm:ss", $null)
$timeendstr = "2020-09-16 09:00:00"
$timeend = [datetime]::ParseExact($timeendstr, "yyyy-MM-dd HH:mm:ss", $null)

$dir = "path\to\parent\folder"

Get-ChildItem -Recurse -File $dir |
    Where-Object {$_.LastWriteTime -gt $timestart -and $_.LastWriteTime -lt $timeend} |
        Select-Object Name,LastWriteTime,@{N='SizeMB';E={[double]('{0:N2}' -f ($_.Length/1MB))}}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.26 09:06:04