Home > database >  How can I append the creation date to all files in a folder and the subfolders in PowerShell?
How can I append the creation date to all files in a folder and the subfolders in PowerShell?

Time:11-25

I have a small script that can successfully copy all the files from folders and subfolders and append the creation time, but the files in the subfolders do not have the creation time appended to their names.

How can I append the creation date to all files in a folder and the subfolders?

My current script is:

$path = "C:\test1"
$destination = "C:\test2"

Get-ChildItem -path $path | ForEach-Object{
        $newname = $_.CreationTime.toString("yyyy-MM-dd")   $_.BaseName  $_.Extension
        (Copy-Item -Recurse -Path $_.FullName -Destination ( Join-Path  $destination $newname)) 
}

CodePudding user response:

You were really close, but the -Recurse switch should have been on Get-ChildItem and within the loop you need to make sure the destination subfolder paths exist.

Try

$source      = "C:\test1"
$destination = "C:\test2"

Get-ChildItem -Path $source -File -Recurse | ForEach-Object {
    # create the new target folderpath for the copy
    $targetPath = Join-Path -Path $destination -ChildPath $_.DirectoryName.Substring($source.Length)
    # make sure the target path exists, if not create it
    $null = New-Item -ItemType Directory -Path $targetPath -Force
    # create a new filename with CreationDate prefixed
    $newName = '{0:yyy-MM-dd}{1}{2}' -f $_.CreationTime, $_.BaseName, $_.Extension
    # copy the file
    $_ | Copy-Item -Destination (Join-Path -Path $targetPath -ChildPath $newname) -Force
}

CodePudding user response:

While you could create your own recursive method to copy files and rename them as you go, it would be easier to use Copy-Item recursively and rename the files and folders afterwards:

$Source = "src"
$Destination = "dst"

Copy-Item -Recurse $Source $Destination

foreach ($Item in (Get-ChildItem -Recurse -File $Destination)) {
    Rename-Item $Item ($Item.Name   "-"   $Item.CreationTime.toString("yyyy-MM-dd"))
}
  • Related