Cmdlet 文件系统操作

文件系统操作是 PowerShell 中最常见、最实用的任务之一。

从创建、复制、移动、删除文件,到获取文件属性、批量处理目录结构,PowerShell 提供了大量简洁而强大的 Cmdlet 来完成这些操作。


一、查看目录内容:Get-ChildItem

Get-ChildItem

这是 PowerShell 中查看目录内容(相当于 ls 或 dir)的命令。默认列出当前目录下的所有文件和子目录。

你也可以使用路径参数:

Get-ChildItem -Path C:\Test

查看所有子目录(递归):

Get-ChildItem -Path C:\Test -ReC++urse

按文件类型筛选:

Get-ChildItem -Path C:\Test -Filter *.txt

二、创建文件和目录:New-Item

创建新目录:

New-Item -Path "C:\Demo" -ItemType Directory

创建新文件:

New-Item -Path "C:\Demo\example.txt" -ItemType File

提示:如路径中父目录不存在,将报错。需先手动或脚本创建上级目录。


三、复制与移动:Copy-Item 和 Move-Item

复制文件:

Copy-Item -Path "C:\Demo\example.txt" -Destination "D:\Backup"

复制整个文件夹(包含内容):

Copy-Item -Path "C:\Demo" -Destination "D:\Backup" -Recurse

移动文件:

Move-Item -Path "C:\Demo\example.txt" -Destination "C:\Demo2"

四、删除文件和目录:Remove-Item

删除文件:

Remove-Item -Path "C:\Demo\example.txt"

删除文件夹及其内容:

Get-ChildItem -Path C:\Test0

说明:

  • -Recurse:删除目录下的所有内容

  • -Force:强制删除隐藏或只读文件


五、读取和写入文件:Get-Content / Set-Content / Add-Content

读取文件内容:

Get-ChildItem -Path C:\Test1

写入内容(覆盖):

Get-ChildItem -Path C:\Test2

追加内容:

Get-ChildItem -Path C:\Test3

六、文件重命名与存在性判断

重命名文件:

Get-ChildItem -Path C:\Test4

判断文件是否存在:

Get-ChildItem -Path C:\Test5

如果存在返回 True,否则返回 False。


七、获取文件属性:Get-Item

Get-ChildItem -Path C:\Test6

注意:返回的是 System.IO.FileInfo 类型对象,可进一步使用对象属性。


八、组合操作示例:批量处理文件

批量列出目录下所有 .log 文件大小总和:

Get-ChildItem -Path "C:\Logs" -Filter *.log | Measure-Object -Property Length -Sum

输出结果示例:

Get-ChildItem -Path C:\Test8

将所有 .txt 文件内容追加到一个新文件中:

Get-ChildItem -Path "C:\TextFiles" -Filter *.txt | ForEach-Object {
    Get-Content $_.FullName | Add-Content -Path "C:\AllText.txt"}

九、注意事项与常见坑

问题说明
路径中包含空格使用引号 " 括起来整个路径字符串
区分目录和文件New-Item 必须指定 -ItemType File 或 Directory
文件不存在时操作报错使用 Test-Path 检查再处理
删除命令需小心Remove-Item 使用 -Recurse 时慎重,避免误删

十、小结与建议

PowerShell 在文件系统操作方面表现非常强大,具备以下优势:

  • 命令直观、统一,学习成本低

  • 支持对象操作,可与其他命令组合

  • 可用于批量任务和自动化脚本

建议学习方式:

  1. 在临时目录中反复练习各类命令

  2. 熟练掌握五个核心命令:New-ItemRemove-ItemCopy-ItemGet-ContentSet-Content

  3. 尝试将命令封装为脚本,批量处理多个文件