Search code examples
powershellrenaming

How do I rename files in a folder based on specific content in each file using PowerShell?


I need to copy an application's archived files (they are all XML), then rename the files with the Customer ID and Purchase Order Number. To find those values, I needed to split the data on the element tags in order to find the index value, then get the values I need based on each index. A few days ago, when I completed the code, it worked as expected. The next day, tried to run it again, and it renamed all files with the same name. When I validated the code (by adding "What-if" or "Write-Host"), I can see the unique filenames. I have tried to get it to work again, but to no avail. I have sample XML documents, if needed.

Here is the code (that once worked):

        ForEach ($f in Get-ChildItem -path "C:\Archive\XML_Processed\Inbound\945-WHS_ShipAdvice_SW\" -Filter IB_945*.xml | Sort-Object) 
        {
            $indxPatt1 = '<e03_0373>'      ##Split Attribute/Element Tag in XML
            $indx1 = (Get-Content $f.fullname) | Select-String -Pattern $indxPatt1 |  ForEach-Object {$_.LineNumber} | Select-Object
            $var1A = (Get-Content $f.fullname) | Select -Index $indx1 
            $patt1A = '<e04_0145>'
            $patt2A = '</e04_0145>'
            $var2A = (Get-Content $f.fullname) | Select-String -Pattern $var1A  | Foreach-Object {$_  -replace $patt1A, ""} 
            $var2B = $var2A  | Foreach-Object {$_  -replace $patt2A, ""} 
            $var3C1 = $var2B | Foreach-Object {$_  -replace " {1,30}", ""}
            $var4A = $var3C1 | Foreach-Object {$_  -replace "^", "OrdNo_"}
            $varTP1B = (Get-Content $f.fullname) | Select -Index 5
            $pattTP1B = '<TradingPartner>'
            $pattTP2B = '</TradingPartner>'
            $varTP2B = (Get-Content $f.fullname) | Select-String -Pattern $varTP1B | Foreach-Object {$_  -replace $pattTP1B, ""} 
            $varTP3B = $varTP2B | Foreach-Object {$_  -replace $pattTP2B, ""}
            $var3TPD1 = $varTP3B | Foreach-Object {$_  -replace " {1,30}", ""}
            $varTP3D2 = $var3TPD1 | Foreach-Object {$_  -replace "^", "CustID_"}
            $varNewName = $varTP3D2 + "_" + $var4A  ##| Write-Host}
            Get-ChildItem C:\Archive\XML_Processed\Inbound\945-WHS_ShipAdvice_SW -Filter *.xml | rename-item -newname { $_.Name -replace 'IB_945', $varNewName};   ##-WhatIf;
        }

Solution

  • If I understand what you're trying to do properly (which is hard without the input data) then (probably) your final line should be changed to:

    $f | Rename-Item -Newname { $f.Name -replace 'IB_945', $varNewName} -WhatIf