1

I try to make Script who can move Files older 31 Days and if a file already exists in Destination, the moving File shall be renamed.

I didnt get that happen.

The Code so far is :

Start-Transcript -Path "D:\LOG\LOG_OLDFILES.txt" -append
get-childitem -verbose -Path D:\DATASOURCE -File -Recurse |
where-object {$_.LastWriteTime -lt (get-date).AddDays(-31)} |
move-item -verbose -destination "D:\temp\temp_backup"

So the moving happens, but i get the Failure :

move-item : Cannot create a file when that file already exists.

In that Case he shall rename it to "Filename_"DATE" "

Hope you can help. I tried hard, but i didnt get some If-then things working.

Thank you!

rzhell
  • 35
  • 5
  • 1
    You want to put your move-item into a try/catch block, this docs page should help you https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_try_catch_finally?view=powershell-7.2 – Jonathan Waring Nov 11 '21 at 11:27
  • For a try/catch block to work, you'd also pass `-ErrorAction Stop` or set `$ErrorActionPreference = 'Stop'` to throw an exception if a cmdlet fails. Another way would be to query the success state variable `$?` but IMO exceptions are cleaner and easier to maintain. – zett42 Nov 11 '21 at 12:56
  • Possible duplicate of [Powershell Select Option Copy, But keep both files - by default](https://stackoverflow.com/questions/65014451/powershell-select-option-copy-but-keep-both-files-by-default) – Theo Nov 11 '21 at 12:58
  • @JonathanWaring Thanks, i will read the Thread! @zett42 Hmm... when i work with ```-ErrorAction Stop``` i would need to write the "Errorfile" into a variable and move them separately? – rzhell Nov 11 '21 at 14:39
  • @Theo Thanks, i will read the Thread! :) – rzhell Nov 11 '21 at 14:39

0 Answers0