2012-04-23 43 views
0

在Powershell中,我想自动执行更改一组文件的文件名并将最新版本的类似文件复制到该目录的过程。Powershell脚本文件名增量

  1. 从另一个目录中删除当前文件的最古老的

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

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

    (newestfile.txt) --> (file1.bak) 
    

这是据我已经变得和我坚持:

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

回答

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

像这样的事情?删除' - Wtif的做真正的事情。

$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 } 
} 
+0

尽管排序是不必要的复杂; 'Sort-Object LastWriteTime'做同样的事情(为了更好的可读性,我总是在脚本中编写整个命令)。 – 2012-04-24 08:29:20

相关问题