PowerShell 常用文件操作
May 19, 2024About 2 min
PowerShell 常用文件操作
写打包/构建脚本时反复用到的 PowerShell 片段,集中记一下。多数是围绕"读文件→按行处理→写回"这个套路。
取当前路径字符串
pwd | ForEach-Object { $_.Path }
pwd 返回的是对象,要纯字符串就取 .Path。
按反斜杠分割 UNC 路径
-split 默认走正则,反斜杠要转义,用 SimpleMatch 选项当字面量更省心:
$path = '\\<server>\<share>\<build>\x64\<build>_Release'
$splitPath = $path -split '\\', -1, 'SimpleMatch'
去除文件只读属性
(Get-Item $file).IsReadOnly = $false
构建产物从 P4/版本库同步下来常带只读属性,改写前先去掉。
删除匹配某模式的行
读全文,逐行判断,命中就替成空串(或直接丢弃),再写回:
$content = Get-Content $iniFile | ForEach-Object -Process {
if ($_ -match 'ERR_X_Error.*SAVING : Bad Current State.*') { '' } else { $_ }
}
$content | Out-File -Encoding utf8 -FilePath $iniFile
在匹配行后追加内容
命中某行时,把原行接上要追加的内容再输出:
$content = Get-Content $shaderFile | ForEach-Object -Process {
if ($_ -match '#if defined.*__SCE__.*_XBOX_SCARLETT') {
$_ + "|| defined($ENV:platformShader)"
} else { $_ }
}
$content | Out-File -Encoding utf8 -FilePath $shaderFile
多个替换串到一起
-replace 可以链着写,一次过一遍文件改多处:
$content = Get-Content $buildIni | ForEach-Object -Process {
$_ -replace '<DisplayVersion>.*</DisplayVersion>', "<DisplayVersion>${MasterVersion}.${build_Version}</DisplayVersion>" `
-replace 'Version = .*', "Version = ${MasterVersion}.${build_Version}" `
-replace 'Label = .*', "Label = $BuildLabel" `
-replace 'BranchName = .*', "BranchName = $BRANCH_NAME" `
-replace 'RevisionNumber = .*', "RevisionNumber = $RevisionNumber"
}
$content | Out-File -Encoding utf8 -FilePath $buildIni
检查文件是否存在并删除
Test-Path 支持通配符:
if (Test-Path "App_Crash_*.dump") {
Remove-Item "App_Crash_*" -ErrorAction SilentlyContinue
}
文件不存在则创建并写入
Add-Content 在目标不存在时会自动创建:
Add-Content -Path "${name}_error.txt" -Value ($line)
递归找隐藏文件/文件夹
-Force 才会把隐藏和系统项算进来,再用 Where-Object 按属性筛:
Get-ChildItem -Path "E:\project\Client" -Recurse -Force |
Where-Object { $_.Attributes -match "Hidden" } |
Select-Object FullName
递归列出所有文件并导出
-File 只列文件不含目录,结果写到 txt:
Get-ChildItem -Path "E:\project\Asset" -Recurse -File -Force |
Select-Object FullName |
Out-File -FilePath "E:\project\filelist.txt"