Reputation: 43
Within Powershell I want to automate the process of changing the file name of a group of files and copy the latest version of a similar file to that directory.
Delete oldest
(file3.bak) --> none
Increase filename of current files in backup directory
(file1.bak) --> (file2.bak)
(file2.bak) --> (file3.bak)
Copy latest version of file from another directory to this backup directory
(newestfile.txt) --> (file1.bak)
This is as far as I have gotten and am stuck:
$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-- }
Upvotes: 0
Views: 8406
Reputation: 43
Thanks to all who responded. Your help was appreciated
#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-- }
Upvotes: 1
Reputation: 43459
Something like this? Remove '-Whatif's to do the real thing.
$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 }
}
Upvotes: 1