powershell

Renaming files within multiple directories


I need to rename files within folders. The folders follow this naming sequence: vdl-1984-01, vdl-1984-02, vdl-1984-03, etc. I only have access to powershell at work and all the fields are tiffs so I have been using

$i=1
Get-ChildItem *.tiff | %{Rename-Item $_ -NewName ('vdl-1984-01-{0:D3}.tiff' -f $i++)}

on each folder. However, I would like a script that runs this function for every folder. Is this possible? In this example, the two digit number is the folder number and the three digit generated number is the file number.

I have been trying to set of up a Do Loop that includes an increasing interval in the CD function and the -NewName function but I cannot seem to get something that works.


Solution

  • Perhaps this works for you, essentially instead of searching for all .tiff files you search for all directories starting with vdl-1984- and from there, for each directory you target their child files using the parent folder name plus - and the 3 digit sequence.

    $parentPath = 'path\to\vdlFolders'
    # get all directories under the parent folder having a name that starts with `vdl-1984-`
    Get-ChildItem $parentPath -Directory -Filter vdl-1984-* | ForEach-Object {
        $index = @(0); $parentName = $_.Name
        # for each directory, get their child files
        $_ | Get-ChildItem -File | Rename-Item -NewName {
            # and rename using the parent folder name + the 3 digit incrementing number
            "$parentName-{0:D3}.tiff" -f $index[0]++
        }
    }
    

    This code would also work if you wanted to hardcode the path of each vdl-1984- folder, but here you want to use Get-Item instead of Get-ChildItem, for example:

    $vdlFolders = @(
        'path\to\vdl-1984-01'
        'path\to\vdl-1984-02'
        'path\to\vdl-1984-03'
    )
    
    $vdlFolders | Get-Item | ForEach-Object {
        # renaming logic here remains the same
    }