文件与路径
Get-ChildItem、Copy-Item、路径引号。
30 分钟
文件与路径
Windows 路径含反斜杠 \,PowerShell 同时接受 /。Get-ChildItem、Copy-Item、Test-Path 是日常文件操作三件套——打包、同步课程、查日志都靠它们。
学习目标
- 正确处理 Windows 路径与引号
- 使用
Get-ChildItem、Copy-Item、Join-Path - 读写文本文件与递归搜索
核心内容
路径基础
Get-Location
Set-Location H:\work\java-nav
Join-Path $PSScriptRoot "..\..\content\课程" # 拼接,自动处理分隔符
Resolve-Path deploy\scripts\sync-courses.ps1 # 转为绝对路径
Test-Path platform\bin\package-prod.bat # 文件是否存在
路径含空格时必须引号:Set-Location "H:\work\my project"。
列出与搜索
Get-ChildItem content\课程 -Directory
Get-ChildItem content\课程\powershell-essentials\drafts -Filter *.md
Get-ChildItem . -Recurse -Filter *.ps1 |
Select-Object FullName, Length
-Recurse 递归子目录;-Filter 比 -Include 更快。对应 Linux:find / ls -R(linux-files)。
复制与移动
Copy-Item deploy\env\prod\platform.env.example platform\.env.production.local
Move-Item logs\old.log logs\archive\
New-Item -ItemType Directory -Path logs\archive -Force
Remove-Item temp\* -Recurse -Force # 谨慎,先 -WhatIf
package-prod.bat 第一步就是 copy deploy\env\prod\platform.env.example → .env.production.local。
读写文本
Get-Content platform\.env.production.local | Select-Object -First 5
"deploy at $(Get-Date)" | Add-Content logs\deploy.log
@(
"line1",
"line2"
) | Set-Content config\test.txt
Set-Content 覆盖;Add-Content 追加。UTF-8 文件:Get-Content -Encoding utf8。
练习
- 递归列出
content\课程下所有outline.yaml - 用
Test-Path确认deploy\scripts\sync-courses.ps1存在 - 复制 到临时目录并读取前 3 行