我重命名一个目录中的所有文件并更换内容以保存它们并将它们另存为新文件
为什么当我回显$ newText的值时它会显示所有文本,但是当我将同一个变量传递给new-item时,我只得到最后一行?
示例...在当前目录中,我有一个名为TemplateClient_.TemplateProject_.txt
的文件,其中包含3行文字
TemplateClient_/TemplateProject_
test text
end
当我运行powershell脚本时,它会创建文件Aaaa.Bbbb.txt
,但它只有一行,即最后一行。它只是说end
$text = get-content $file.fullname
$newText = $text -creplace $currentClient,$newClient
$newText = $newText -creplace $currentProject,$newProject
echo $newText
$newFileLoc = $file.fullname.replace($currentClient, $newClient).replace($currentProject, $newProject)
$newText | new-item -force -path $newFileLoc -type "file"
解决方案:
$currentClient = "TemplateClient_"
$currentProject = "TemplateProject_"
$newClient = "Aaaa"
$newProject = "Bbbb"
$files = Get-ChildItem $(get-location) -include *.txt -Recurse
foreach($file in $files)
{
$fileText = get-content $file.fullname
$fileText = $fileText -creplace $currentClient,$newClient
$fileText = $fileText -creplace $currentProject,$newProject
$newFileLoc = $file.fullname.replace($currentClient, $newClient).replace($currentProject, $newProject)
new-item -force -path $newFileLoc -type "file"
Set-Content $fileText -Path $newFileLoc
}
答案 0 :(得分:2)
怎么样
Set-Content $newText -Path $newFileLoc
或
$newText | Set-Content $newFileLoc