使用字符串变量作为Set-Content -Path的输入

时间:2011-12-25 21:02:20

标签: powershell

我有以下脚本循环遍历文本文件,用b替换字母a

  

$ fileList = Get-ChildItem C:\ Projekte \ ps

     

foreach($ file in $ fileList){(Get-Content -Path $ i.FullName)-replace'a','b'| Set-Content -Path $ i.FullName}

我工作,结果写回原始文件。我需要将内容写回新文件。该文件的名称是原始文件,但扩展名为“.new”

我期待像

这样的东西
  

Set-Content -Path $ i.FullName +'。new'

但那显然是错的。

这个问题的正确语法是什么?

1 个答案:

答案 0 :(得分:2)

我建议你)在列表中)过滤文本文件,因此对于可能位于该文件夹中的其他文件扩展名不会发生替换:

$fileList = Get-ChildItem D:\Scripts\Temp -Filter *.txt

foreach($i in $fileList)
{
    $path = Join-Path -Path $i.DirectoryName -ChildPath ($i.BaseName + '.new')
    (Get-Content -Path $i.FullName) -replace 'a','b' | Set-Content -Path $path
}
相关问题