列出文件系统、注册表等提供程序中的条目,输出可继续过滤的对象。
Get-ChildItem 枚举指定路径的直接子项,输出 System.IO.FileInfo / DirectoryInfo(注册表提供程序则输出注册表键对象),不是格式化文本。常见别名是 gci、ls、dir;它支持 -File、-Directory、-Recurse、-Depth、-Force、-Filter,结果的 FullName、Length、LastWriteTime、Attributes 可直接参与管道运算。
管道:-Path 可按属性名接收字符串,不消费 FileInfo 对象;要按大小、时间筛选请接 Where-Object。权限:读取目录需要 LIST/READ 权限,无权访问的子目录产生非终止错误,后续条目继续输出,脚本不一定失败。需要管理员才能看全其他用户的目录和部分系统路径。
版本:5.1 只有 Windows 提供程序,-File、-Directory、-Depth 已可用。7.x 差异:增加 Unix 文件系统提供程序,隐藏项靠点号而不是 Hidden 属性,并支持 -FollowSymlink;跨平台脚本不要依赖 Attributes 判断 Unix 隐藏文件。
# 1. 找最大的日志文件,先排序再截断,避免输出过多
PS C:\> Get-ChildItem C:\Logs -File | Sort-Object Length -Descending | Select-Object -First 5 Name, Length, LastWriteTime
# 2. 统计 DLL 总大小;Length 只对文件有意义
PS C:\> Get-ChildItem C:\Windows\System32 -Filter *.dll -File | Measure-Object -Property Length -Sum
# 3. 递归找最近 7 天改过的文件;权限错误只记录不中断
PS C:\> Get-ChildItem C:\Apps -Recurse -Force -ErrorAction SilentlyContinue | Where-Object LastWriteTime -gt (Get-Date).AddDays(-7)
# 4. 用注册表提供程序列出已安装程序的子键
PS C:\> Get-ChildItem HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall | Select-Object -First 5 PSChildName
# 5. 用通配符定位特定前缀的目录
PS C:\> Get-ChildItem C:\ProgramData -Directory -Filter 'Microsoft*' | Select-Object Name, FullName
# 6. 只看隐藏项,Attributes 是位标志而非布尔值
PS C:\> Get-ChildItem C:\Windows\Temp -Force | Where-Object { $_.Attributes -band [IO.FileAttributes]::Hidden }
-Include *.log 却没有 -Recurse 或路径通配符,结果为空;-Include 需要 -Recurse 或 C:\Logs\* 这样的路径展开才生效。修正:用 -Filter *.log,或 -Path C:\Logs\* -Include *.log -Recurse。-Filter 由提供程序执行,速度快但语义不完全等同通配符,还可能匹配 8.3 短名;验证时用 -Include 或 Where-Object Name -like 对比结果。-ErrorAction SilentlyContinue -ErrorVariable err 后检查 $err.Count,或对已知目录提权。Length 通常为空,Measure-Object Length -Sum 只统计文件;统计目录内容要单独递归求和。dir 在 PowerShell 里是别名,不接受 CMD 的 /a、/s;在 PowerShell 中写 dir /a 会把 /a 当路径。需要 CMD 语义时调用 cmd /c dir /a。-Force 只显示隐藏/系统项,不绕过 ACL;无权目录即使加 -Force 仍然拒绝访问。. 开头,-Hidden 和 Attributes 不可靠;符号链接默认不跟随,需要 -FollowSymlink。dir — CMD 的目录列表,语义和参数都不同。Get-Content — 读取找到的文本文件。Select-String — 在递归结果中搜索内容。Where-Object — 按属性筛选文件对象。合上页面,先回答,再展开对照。
Get-ChildItem 输出的是字符串还是对象?这对后续 Where-Object 有什么影响?Get-ChildItem C:\Logs -Include *.log 可能什么都找不到?FileInfo/DirectoryInfo 等对象;后续可按 Length、LastWriteTime 等属性筛选,不需要解析文本。-Include 需要 -Recurse 或路径中的通配符才会展开;改用 -Filter 或 -Path C:\Logs\* -Include *.log。-ErrorVariable 收集后检查数量,或 -ErrorAction Stop 让它失败。
小程序版
微信扫码,随时查命令