线路可能无法正确转义

Line may not be escaping properly

我已经为此工作了几个小时,无法弄清楚我可能遗漏了什么。基本上,我得到了文件夹和子文件夹中所有 XML 文件的列表。循环遍历这些文件,我用另一个字符串替换一个字符串,然后将其写回同一个文件。下面是我正在使用的行:

$destination = "C:\Temp\TestFolder"
$newString = "#NewString#"

Get-ChildItem '$($destination)*.xml' -Recurse | ForEach {
    $currFile = $_.FullName; 
    (Get-Content $_ | ForEach {
        $_ -Replace '#OldString#', '$($newString)'
    }) | Set-Content -Path $currFile;
}

问题是您实际上没有指向正确的目录。

当你运行这个命令时:

Get-ChildItem '$($destination)*.xml' -Recurse 

您使用的是单引号。单引号不允许字符串扩展,就像您尝试使用 $($destination) 一样。当 PowerShell 运行 执行此操作时,它实际上是在名为 $($destination) 的路径中查找文件,该路径将不存在。

相反,将它们替换为双引号,或者更好的是,完全删除引号。

Get-ChildItem $destination\*.xml -Recurse 

最后,您不需要使用 For-Each 循环来替换该字符串的所有实例。可以调用 Get-Content,然后调用 replace,最后将值全部设置在一行中,如下所示:

$files = Get-ChildItem $destination\*.xml -Recurse 
ForEach ($file in $files){ 
  Set-Content ((Get-Content $File.FullName) -Replace '#OldString#', $newString) `
    -Path $file.fullname 
}