PowerShell 根据字典循环替换指定目录下所有文件中的字符串
PS:
# 定义要搜索的目录和关键字-替换字符串对 $directory = "D:\xxx\xxx" $replacements = @{ "<variable_type>JVM</variable_type>" = "<variable_type>CURRENT_JOB</variable_type>" "<variable_type>PARENT_JOB</variable_type>" = "<variable_type>CURRENT_JOB</variable_type>" "<variable_type>ROOT_JOB</variable_type>" = "<variable_type>CURRENT_JOB</variable_type>" } # 获取所有 .kjb 和 .ktr 文件 Get-ChildItem -Path $directory -Recurse -Include *.kjb, *.ktr | ForEach-Object { $filePath = $_.FullName $content = Get-Content -Path $filePath # 遍历每个关键字-替换字符串对进行替换 foreach ($key in $replacements.Keys) { $content = $content -replace [regex]::Escape($key), $replacements[$key] $matches = Select-String -Path $filePath -Pattern $key if ($matches) { $newContent = $content -replace [regex]::Escape($key), $replacements[$key] # 将修改后的内容写回文件 $newContent | Set-Content -Path $filePath Write-Output "Replaced keyword in file: $filePath $key" } } }
Reference
Get-ChildItemForEach-Object
Select-String
Set-Content