#文件与目录
PowerShell 提供了一组用于创建、浏览、复制、移动、重命名和删除文件与目录的命令。这些命令通过 FileSystem 提供程序工作,在 Windows、Linux 和 macOS 上都可以使用。
#列出目录内容
> Get-ChildItem
> Get-ChildItem -Path ./src -File -Recurse
> Get-ChildItem -Path . -Directory
> Get-ChildItem -Path . -Filter *.ps1
-File只返回文件,-Directory只返回目录。-Recurse递归处理子目录。-Filter使用提供程序的筛选语法,通常比通配符-Path更高效。
#创建文件和目录
> New-Item -ItemType Directory -Path ./demo
> New-Item -ItemType File -Path ./demo/note.txt
-ItemType 常用值为 File 和 Directory。创建文件时会生成一个空文件。
#复制、移动、重命名和删除
> Copy-Item -Path ./demo/note.txt -Destination ./demo/note.bak
> Move-Item -Path ./demo/note.bak -Destination ./demo/backup.txt
> Rename-Item -Path ./demo/backup.txt -NewName archive.txt
> Remove-Item -Path ./demo/archive.txt
删除目录及其内容,操作前可以先用 -WhatIf 预览:
> Remove-Item -Path ./demo -Recurse -WhatIf
> Remove-Item -Path ./demo -Recurse
#测试路径
> Test-Path -Path ./demo/note.txt
> Test-Path -Path ./demo -PathType Container
> Test-Path -Path ./demo/missing.txt -PathType Leaf
-PathType Container检查目录,-PathType Leaf检查文件,返回布尔值。
#读取和写入内容
> Get-Content -Path ./demo/note.txt
> Set-Content -Path ./demo/note.txt -Value 'hello'
> Add-Content -Path ./demo/note.txt -Value 'world'
> Get-Content -Path ./demo/note.txt
Get-Content默认按行读取,Set-Content覆盖文件内容,Add-Content追加内容。
#-Path 与 -LiteralPath
-Path 支持通配符,-LiteralPath 则按字面值处理路径:
> Get-Content -Path ./logs/*.txt
> Get-Content -LiteralPath './data[1].txt'
当文件名包含 [、]、*、? 等通配符字符时,应使用 -LiteralPath,否则路径可能被当作通配符展开。
#通配符
| 通配符 | 说明 |
|---|---|
* | 匹配任意数量字符 |
? | 匹配单个字符 |
[abc] | 匹配括号中的任意一个字符 |
[a-z] | 匹配指定范围内的字符 |
#注意事项
- 包含空格的路径应使用引号包裹。
-Path与-LiteralPath的区别在文件名包含特殊字符时尤其重要。- 跨平台脚本建议使用
Join-Path拼接路径,避免硬编码路径分隔符。