首页 > 解决方案 > Powershell重命名目录中的文件

问题描述

$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 }
#}

来自定义的 ht 的复制部分正在工作,现在在我复制文件夹和每个我想要添加到该文件夹​​中每个文件的日期和时间的内容之后,但不更改目标文件夹的名称。最后一部分仍然让我头疼,因为当我从源复制文件夹及其内容时,尝试重命名文件夹时也会重命名文件夹,我只想要文件夹的内容。例如,如果我有包含 50 个项目的文件夹 LAA,我希望只添加这 50 个项目,并将其重命名如下,并带有创建日期和时间。

标签: powershellpowershell-4.0

解决方案


您可以在同一个循环中复制具有新名称的文件,如下所示:

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)
    }
}

希望有帮助


推荐阅读