Powershell rename the files from a directory

ぃ、小莉子 提交于 2020-05-28 11:51:05

问题


$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.


回答1:


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



来源:https://stackoverflow.com/questions/61792731/powershell-rename-the-files-from-a-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!