线路可能无法正常转义

时间:2017-01-11 16:40:27

标签: powershell powershell-v3.0

我已经在这方面工作了几个小时,并且无法弄清楚我可能缺少的东西。基本上,我获取了文件夹和子文件夹中所有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;
}

1 个答案:

答案 0 :(得分:3)

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

运行此命令时:

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

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

相反,用双引号替换它们,甚至更好,删除引号fullley。

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 
}
相关问题