Search code examples
powershellpowershell-4.0

Powershell rename the files from a directory


$ht = @{}
$o = new-object PSObject -property @{ 
    from = "C:\Users\nicolae.calimanu\Documents\scripturi copiere\LAA"
    to = "C:\Users\nicolae.calimanu\Documents\scripturi copiere\destinatie" }
$ht.Add($o.from, $o) 

$o = new-object PSObject -property @{ 
    from = "C:\Users\nicolae.calimanu\Documents\scripturi copiere\LBB"
    to = "C:\Users\nicolae.calimanu\Documents\scripturi copiere\destinatie" }
$ht.Add($o.from, $o) 

$o = new-object PSObject -property @{ 
    from = "C:\Users\nicolae.calimanu\Documents\scripturi copiere\LCC"
    to = "C:\Users\nicolae.calimanu\Documents\scripturi copiere\destinatie" }
$ht.Add($o.from, $o) 

foreach($server in $ht.keys  ) {

            copy-item $ht.Item($server).from -destination $ht.Item($server).to -Recurse ;

             }
#  rename
##$destination = "C:\Users\nicolae.calimanu\Documents\scripturi copiere\destinatie"
#foreach($fisier in $destination) {
 #   Get-ChildItem $fisier | 
  #  Rename-Item -NewName {$_.Basename + '_' + $_.CreationTime.Year + $_.CreationTime.Month + $_.CreationTime.Day + '_'+ $_.CreationTime.Hour + $_.CreationTime.Minute + $_.Extension }
#}

The copy part from the defined ht is working, now after I copy the folder and the contents of each I want to add to each file in that folder the date and time, but without changing the name of the folder of the destination. The last part is stilling giving me a headache as when I copy the folders from the source with its content when trying to rename it renames the folder too, and I want it only what the content of the folder has. for example if I have the folder LAA with 50 items, I want only those 50 items to be added renamed as below, with the creation date and time.


Solution

  • You can copy the files with their new name in the same loop like this:

    foreach($server in $ht.keys  ) {
        # for clarity..
        $source      = $ht.Item($server).from
        $destination = $ht.Item($server).to
    
        Get-ChildItem -Path $source -File -Recurse | ForEach-Object {
            # create the target path for the file
            $targetPath = Join-Path -Path $destination -ChildPath $_.FullName.Substring($source.Length)
            # test if this path exists already and if not, create it
            if (!(Test-Path $target -PathType Container)) {
                $null = New-Item -ItemType Directory -Path $targetPath
            }
            # create the new file name
            $newName = '{0}_{1:yyyyMMdd_HHmm}{2}' -f $_.BaseName, $_.CreationTime, $_.Extension
            $_ | Copy-Item -Destination (Join-Path -Path $targetPath -ChildPath $newName)
        }
    }
    

    Hope that helps