![](/img/trans.png)
[英]Powershell script to find file name in a file and move it to a different directory
[英]powershell script isn't working, but shows no errors. Find all .xml files in a directory, do a replace on some text, move to different directory
powershell 腳本錯誤了幾次 b/c 遺漏的逗號等。 現在它似乎運行沒有錯誤,但沒有任何反應——文件沒有移動,文本沒有被替換。
僅供參考,我讓替換自己工作 - 它掃描了所有 .XML 文件並用較大的字符串替換了那個小字符串。 替換確實包括 XML 中需要的新行和空格,但我在此示例中對其進行了簡化,以便於閱讀。
一如既往,非常感謝所有幫助。
編輯:添加解決方案。 謝謝你,TheMadTechnician
$CurrFilePath = "C:\Folder\Path1"
$TransIncludePattern = "*.xml"
$ProcessFilePath = "C:\Folder\Path2"
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:\Folder\Path1"
$TransIncludePattern = "*.xml"
$ProcessFilePath = "C:\Folder\Path2"
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.