开发者

Selective file renaming in Powershell

开发者 https://www.devze.com 2023-02-07 04:58 出处:网络
I\'ve got a large directory of files, many (but not all) of which have been backed up in place by means of copying them and inserting .backup inbetween their filename and extension. Using PowerShell I

I've got a large directory of files, many (but not all) of which have been backed up in place by means of copying them and inserting .backup inbetween their filename and extension. Using PowerShell I would like to create another backup of only the files that have already been backed up once, this time tagged with .backup.(date).

I'm still very new to powershell so I'm a bit shaky the basics. In this case the snag I can't think through is how I would select the files for which there exists an identical filename with .backup. Getting the .backup files I can do, but the开发者_StackOverflow中文版n getting their .backup-less counterparts and passing them to the pipe I can't do yet. Essentially I guess I'm curious about there being a Exists operator for use in where-object or something.

Any ideas?


This should give you a list of the filenames of the ones that have an existing backup:

 $files = gci <directory path> -name
  $backups = $files | where {$_ -match "\.backup\.[^\.]+$"}
  $backedup = $backups | foreach {$_ -replace "backup\."} 
  $newbackups = $backedup | where  {$files -contains $_}

Get the names of all the .backup. files.
Remove the .backup from the name.
See if the original list of files has a name that matches what's left.


Here's what I ended up with.

get-childitem | ?{$_.name -match '.*backup\..*'} | %{$_.name -replace 'backup\.',''} | %{get-childitem $_} | copy-item -destination {$_.name -replace '\.([^.]*)$','.backup.2011-01-25.$1'}

0

精彩评论

暂无评论...
验证码 换一张
取 消