Powershell file mover

Pretty simple script I wrote a while back. Moves files between two paths. For example, to sweep files from a DMZ server. Optionally renames files on the target system by appending a date code. This is to avoid name collisions. Pay close attention to $FileAge, which sets a lower limit on the age of files to copy and $RenameDelay, which sets an upper limit on the age of files to rename in the destination path. Change the copy-item method to the move-item method before going to production.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
set-StrictMode -version 2
 
$FileAge = 30 #age of files in minutes
$RenameDelay = 5 #delay value for renaming files
$Source = "\\server1\path1\" #source folder
$Destination ="\\server2\path2\" #destination folder
 
 
$Past = (Get-Date).AddMinutes($FileAge * -1) 
$Past2 = (Get-Date).AddMinutes($RenameDelay * -1)
 
#first pass - move files form source to destination
$List = dir $Source -recurse | Where {$_.LastWriteTime -lt $Past -and $_.name -notlike "someString*" -and $_.name -notlike "SomeOtherString*"}
if ($list -ne $null){
	write-host $list.count "items found to move"
	foreach($file in $list){
		#$file.Fullname
		If ($file.PSIsContainer -eq $false) {
			$MoveDirectory = (join-path -path $Destination -childpath $file.DirectoryName.SubString(14))
			new-item -path $MoveDirectory -type directory -ErrorAction:SilentlyContinue #create destination folder if it doesn't already exist
		}	
		$MovePath = (join-path -path $Destination -childpath $file.FullName.SubString(15))
		copy-item -Path $file.FullName -destination $MovePath -force #move file to destination folder
	}
}
else {write-host "no matching items found to move"}
 
#second pass - rename files in destination
$List = dir $destination -recurse | Where {$_.CreationTime -gt $Past2 -and $_.PSIsContainer -eq $false -and $_.name -notlike "SomeString*" -and $_.name -notlike "SomeOtherString*" }
if ($list -ne $null){
	write-host $list.count "items found to rename"
	foreach($file in $list){
		$file = ( rename-item -force –path $file.Fullname –Newname ( $file.basename + (get-date -format '_yyyy-MM-dd_hhmm') + $file.extension))
	}
}
else {write-host "no matching items found to rename"}
 
set-StrictMode -Off
This entry was posted in Powershell, Windows OS. Bookmark the permalink.

1 Response to Powershell file mover

  1. Peg says:

    Nice script!

    I was able to use parts of your script to to something similar.

    I needed to move backup files from directory to another based on “DayOfWeek” and filename.

    Thanks for posting your work!
    Peg

Comments are closed.