Need some assistance with Folder and File rename script

I’m looking to take the date time format from the parent folder and append it to all child files under the directory. It won’t be recursive.

So for instance.

Foldername-20151109

File01.txt
File02.txt
File03.txt

After script would run it should look like this…

Foldername-20151109
File01-20151109.txt
File02-20151109.txt
File03-20151109.txt

Any assistance would be greatly appreciated.

There are several ways to accomplish what you are trying to do. Here are some suggestions. Look at Get-ChildItem, Split-Path, and Rename-Item cmdlet. Look at the Directory and/or the DirectoryName property of the files, and look at the -split operator.

You could try

$topFOlder = Get-Item .\Foldername-20151109
$pos = $topFolder.Name.Indexof("-")
$filedate = $topFolder.Name.Substring($pos + 1)


foreach ($file in (Get-ChildItem $topFOlder))
    {
        $ext = $file.Name.Indexof(".")
        $fileName = $file.Name.Substring(0, ($ext))
        Rename-Item "$topFolder\$file" $($fileName +"-" + $filedate + ".txt")
    }

This will also do it. (Note -File is available for get-childitem as of PowerShell version 3.0. It will not work with 2.0. In 2.0 you can use the “PSIsContainer” property)

Get-ChildItem -Path ".\*" -File | Rename-Item -NewName {"$($_.BaseName)-$(($_.DirectoryName -split '-')[1])$($_.Extension)"}

First and foremost thank you very much for you assistance. Here is what i’ve managed to work out that halfway works. (Extracting the date time stamp from parent). Now the Rename item portion is failing. It keeps attempting to find the files on my desktop instead of temp. Any ideas?

# Get the folder list
$folders = (gci "c:\Temp\Directory" | where-object {$_.PSIsContainer -eq $True})
$regex = "20\d{2}[01]\d[0123]\d?"
foreach ($f in $folders) {
    
    $prog = [regex]::match($f, $regex) 
    #Write-Host $prog
    foreach ($file in (Get-ChildItem $f)) {
       
       Rename-Item "$folders\$f\$file" $("$folders\$f\$file" + "-" + $prog)
         

    }
}

Rename-Item : Cannot rename because item at 'xxx-xxx_0_0_wk_pdu-fixed_basic_u_20141217
At C:\Users\xxxx\Desktop\Powershell\RenameFilesByDateonParentFolder.ps1:10 char:8

  •    Rename-Item -path "$folders\$f\$file" -newname $("$folders\$f\$file" + "- ..

@thingsthatdostuff, you are really over complicating things here. Is there a reason that this isn’t working for you?

Get-ChildItem -Path ".\*" -File | Rename-Item -NewName {"$($_.BaseName)-$(($_.DirectoryName -split '-')[1])$($_.Extension)"}