PowerShell 文件系统操作 Cmdlet 完全速查表(2025 最新版)
这些命令在 Windows、Linux、macOS 上全部通用(PowerShell 7+)
| 任务 | 推荐 Cmdlet + 常用参数 | 实战例子(直接复制就能用) |
|---|---|---|
| 列出文件和文件夹 | Get-ChildItem(别名:dir、ls、gci) | Get-ChildItem C:\Windows -Recurse -File |
-Recurse 递归-Directory 只列文件夹-File 只列文件 | dir *.log -Recurse | Where LastWriteTime -gt (Get-Date).AddDays(-7) | |
| 创建文件夹 | New-Item -ItemType Directory | New-Item -Path "D:\备份\2025报告" -ItemType Directory |
简写:mkdir 路径(PowerShell 自动映射) | mkdir D:\Temp\测试 -Force | |
| 创建空文件 | New-Item -ItemType File | New-Item -Path "C:\log\today.log" -ItemType File |
更快写法:Out-File 或 Set-Content | "开始记录" > D:\log\start.txt | |
| 复制文件/文件夹 | Copy-Item(别名:cp、copy) | Copy-Item "D:\项目\*.*" "E:\备份\项目" -Recurse -Force |
| 移动/改名 | Move-Item(别名:mv、move) | Move-Item "C:\1.txt" "D:\归档\2025-12-03.txt" |
| 删除文件/文件夹 | Remove-Item(别名:del、rm、ri) | Remove-Item "D:\Temp\*" -Recurse -Force # 删除 Temp 所有内容 |
安全起见永远加 -WhatIf 先预览 | ri "D:\重要数据" -Recurse -WhatIf | |
| 读取文件内容 | Get-Content(别名:gc、cat、type) | Get-Content .\error.log -Tail 50 # 只看最后 50 行(超实用!) |
| 实时监控日志 | Get-Content .\app.log -Wait -Tail 10 | |
| 写入/追加文件 | Set-Content(覆盖写)Add-Content(追加) | "$(Get-Date) 系统启动" | Add-Content -Path "C:\log\boot.log" |
| 最常用重定向符号 | Get-Process > C:\进程.txt # 覆盖Get-Service >> C:\服务.txt # 追加 | |
| 查找文件 | Get-ChildItem + Where | gci D:\ -Recurse -File -Include *.docx,*.pdf | Where Length -gt 10MB |
| 超快查找(内置索引) | Get-ChildItem D:\ -Filter "*.log" -File | |
| 获取文件属性 | Get-Item(别名:gi) | (Get-Item "C:\1.zip").Length # 文件大小(gi .).LastWriteTime |
| 修改文件时间戳 | (Get-Item 文件).LastWriteTime = 新时间 | (gi "C:\报告.docx").LastWriteTime = "2025-12-01 08:30" |
| 计算文件夹大小 | Get-ChildItem -Recurse | Measure-Object -Property Length -Sum | (gci "D:\电影" -Recurse -File | Measure Length -Sum).Sum /1GB |
| 批量改后缀名 | 经典脚本(必会) | “`powershell |
| 解压与压缩 | Expand-Archive、Compress-Archive | Compress-Archive -Path "D:\项目\*" -DestinationPath "D:\项目备份.zip" -Force |
Expand-Archive -Path "C:\backup.zip" -DestinationPath "C:\恢复\" -Force |
10 个日常必备“一键脚本”模板(直接保存为 .ps1)
# 1. 一键清理临时文件(安全版)
Get-ChildItem $env:TEMP -Recurse -Force | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
# 2. 查找 7 天内修改过的所有文档
Get-ChildItem D:\ -Include *.docx,*.xlsx,*.pdf -Recurse -File |
Where LastWriteTime -gt (Get-Date).AddDays(-7) | Select FullName,LastWriteTime
# 3. 按月份自动归档日志
Get-ChildItem "C:\Logs\*.log" | Group-Object { $_.LastWriteTime.ToString("yyyy-MM") } | ForEach-Object {
$folder = "C:\归档\$($_.Name)"
mkdir $folder -Force
$_.Group | Move-Item -Destination $folder
}
# 4. 监控文件夹变化(热文件夹)
Watch-Path "D:\下载" { Write-Host "有新文件!$args" }
# 5. 批量添加文件前缀(比如加 [备份])
Get-ChildItem "D:\照片\*" | Rename-Item -NewName { "【2025】" + $_.Name }
掌握上面这些,你在文件系统操作上已经超越 99% 的普通用户 + 90% 的运维了!
下一步你想要:
- “文件系统高级技巧”(符号链接、权限 ACL、流数据)?
- “跨网络复制 + 进度条”实战脚本?
- 还是直接来个“企业级自动备份系统”完整案例?
随时说,我继续给你安排最硬核的!