powershell脚本由于缺少逗号等原因出错了几次。现在,它似乎运行时没有任何错误,但什么也没发生——文件没有移动,文本没有被替换。
仅供参考,我让替代品自己工作——它扫描了所有的。XML文件,并用较大的字符串替换了那个小字符串。替换确实包含了XML中需要的新行和空格,但我在这个示例中对其进行了简化,使其更易于阅读。
一如既往,我们非常感谢您的帮助。
编辑:添加了解决方案。谢谢,TheMadTechnician
$CurrFilePath = "C:FolderPath1"
$TransIncludePattern = "*.xml"
$ProcessFilePath = "C:FolderPath2"
try #Get-ChildItem -Path $CurrFilePath* -Include $TransIncludePattern | Select-Object -First 1 | ForEach-Object
{
$CurrFileName = Get-childitem -Path $CurrFilePath* -Include $TransIncludePattern;
$CurrFileName |
Select-Object -ExpandProperty FullName |
ForEach-Object {
Write-Host "Changing file $_";
$content = (Get-Content $_);
$newContent = $content | ForEach-Object {
($_-replace '</InitgPty>', '<Id> <OrgId> <Id>DAMNID</Id> </OrgId> </Id></InitgPty>');
}
$newContent | Set-Content $_; #or [IO.File]::WriteAllLines($_, $newContent) :)
Write-Host "File Changed: $_";
}
Write-Host "Has DamnID";
Move-Item -CurrFileName $file -Destination $ProcessFilePath;
exit 0;
}
catch {
Write-Error $_;
}
工作脚本:
$CurrFilePath = "C:FolderPath1"
$TransIncludePattern = "*.xml"
$ProcessFilePath = "C:FolderPath2"
try #Get-ChildItem -Path $CurrFilePath* -Include $TransIncludePattern | Select-Object -First 1 | ForEach-Object
{
$CurrFileName = Get-childitem -Path $CurrFilePath* -Include $TransIncludePattern;
$CurrFileName |
Select-Object -ExpandProperty FullName |
ForEach-Object {
$content = (Get-Content $_);
$newContent = $content | ForEach-Object {
($_-replace '</InitgPty>', '<Id> <OrgId> <Id>DAMNID</Id> </OrgId> </Id></InitgPty>');
}
$NewContent = Set-Content -Path $_ -Value $newContent;
}
Move-Item -Path .*.xml -Destination $ProcessFilePath;
exit 0;
}
catch {
Write-Error $_;
}
转到Set-Content
时,将丢失$_
的上下文。$newContent = Set-Content $_
我假设$_
应该引用文件名,但此时它包含文件的修改内容。请在该行尝试Set-Content -Path $_ -Value $newContent
。
然后,当您移动文件时,参数-CurrFileName
不是有效的参数。而是使用Move-Item -Path $_ -Destination $ProcessFilePath