Powershell脚本文件名增量

时间:2012-04-23 20:28:12

标签: powershell

在Powershell中我想自动更改一组文件的文件名并将类似文件的最新版本复制到该目录。

  1. 删除最早的

    (file3.bak) --> none
    
  2. 增加备份目录中当前文件的文件名

        (file1.bak) --> (file2.bak)
        (file2.bak) --> (file3.bak)
    
  3. 将最新版本的文件从另一个目录复制到此备份目录

    (newestfile.txt)   --> (file1.bak)
    
  4. 这是我已经得到的并且被卡住了:

    $path = "c:\temp"
    cd $path
    
    $count = (get-childitem $path -name).count
    Write-Host "Number of Files: $count"
    
    $items = Get-ChildItem | Sort Extension -desc | Rename-Item -NewName {"gapr.ear.rollback$count"}
    
    $items | Sort Extension -desc | ForEach-Object  -begin { $count= (get-childitem $path -name).count }  -process { rename-item $_ -NewName "gappr.ear.rollback$count"; $count-- }
    

2 个答案:

答案 0 :(得分:1)

这样的东西?删除'-Whatif's来做真实的事情。

$files = @(gci *.bak | sort @{e={$_.LastWriteTime}; asc=$true})

if ($files)
{
    del $files[0] -Whatif
    for ($i = 1; $i -lt $files.Count; ++$i)
     { ren $files[$i] $files[$i - 1] -Whatif }
}

答案 1 :(得分:1)

感谢所有回复的人。感谢您的帮助


#Directory to complete script in
$path = "c:\temp"
cd $path

#Writes out number of files in directory to console
$count = (get-childitem $path -name).count
Write-Host "Number of Files: $count"

#Sorts items by decsending order
$items = Get-ChildItem | Sort Extension -desc 

#Deletes oldest file by file extension number
del $items[0]

#Copy file from original directory to backup directory
Copy-Item c:\temp2\* c:\temp

#Sorts items by decsending order
$items = Get-ChildItem | Sort Extension -desc

#Renames files in quotes after NewName argument
$items | ForEach-Object  -begin { $count= (get-childitem $path -name).count }  -process { rename-item $_ -NewName "file.bak$count"; $count-- }