The powershell script errored out a few times b/c of missed commas and the like. Now it appears to run with no errors, but nothing happens - files aren't moved, text isn't replaced.
FYI, I got the replace to work by itself - it scanned all the .XML files and replaced that tiny string with the bigger one. The replace does include new lines and spaces as one needs in XML, but I simplified it in this sample so it was easier to read.
As always, all help is greatly appreciated.
EDIT: SOLUTION ADDED. Thank you, 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 $_;
}
Working script:
$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 $_;
}
CodePudding user response:
You lose context of $_
when you go to Set-Content
. $newContent = Set-Content $_
I assume the $_
is supposed to reference the file name, but at that point it contains the modified content of the file. Try Set-Content -Path $_ -Value $newContent
instead on that line.
Then when you move the file the parameter -CurrFileName
is not a valid parameter. Instead use Move-Item -Path $_ -Destination $ProcessFilePath