More than one Rename-Item in Foreach (PS)

215 Views Asked by At

I got multiple files on a folder and I am trying to make a script that does this:

  1. Change the file extension to txt

  2. Replace all periods . to underscores _

  3. Get content inside the text file and rename it depending on the content it took

I want the script to do it file by file.

Note: All the files extensions are different.

First try

Get-ChildItem -Exclude "*.ps1",".txt" | rename-item -NewName  { $_.Name + ".txt" }

Get-ChildItem "*.txt" | Rename-Item -NewName { $_.Basename.Replace('.', '_') + $_.Extension }

Get-ChildItem "*.txt" -Filter *.txt  |
Foreach-Object {
    $content = Get-Content -Raw $_.FullName

    if ($content -match '(?<=serie=")(.*)(?=" folioFiscal)') {
        $Matches[1]
     }

     $string1 = $Matches[1]

    if ($content -match '(?<=folioFiscal=")(.*)(?=" UUID)') {
        $Matches[1]
        }

    $string2 = $Matches[1]

    Rename-Item -Path $_.FullName -NewName  ($string1+"-"+$string2+"_"+$_.Name)

}

It worked but the problem is that if there are already ".txt" files in the folder, it would affect them too, so I am trying to do the same, file by file without taking ".txt" files in consideration.

Second try

Get-ChildItem -Exclude "*.ps1","*.txt"  |
Foreach-Object {

    Rename-Item -Path $_.FullName -NewName  ( $_.Name + ".txt" )
    
    Rename-Item -Path $_.FullName -NewName  ($_.Basename.Replace('.', '_') + $_.Extension)

    $content = Get-Content -Raw $_.FullName 

    if ($content -match '(?<=serie=")(.*)(?=" folioFiscal)') {
        $Matches[1]
    }
        
    $string1 = $Matches[1]
        
    if ($content -match '(?<=folioFiscal=")(.*)(?=" UUID)') {
        $Matches[1]
    }
        
    $string2 = $Matches[1]
        
    Rename-Item -Path $_.FullName -NewName  ($string1+"-"+$string2+"_"+$_.Name)
}

I'm getting a problem with $_.FullName, because after the first Rename-Item, it doesn't change and the next Rename-Item looks for the old file (without ".txt") or that's what I think.

This is the error:

Rename-Item : Cannot rename because item at 'path' does not exist.

Is there any solution for this?

0

There are 0 best solutions below