Move Files Older Than X Days

Hello,

I have the following code that performs the following:   I would like to modify the code to move files older than xdays to a network share.  Can you help please?   I have the following answers from a previous case to delete files older than x days here: http://www.experts-exchange.com/Programming/Languages/Scripting/Powershell/Q_28601783.html

Script Begin
[CmdletBinding(SupportsShouldProcess=$True)]
Param(
	[string]$Path = "C:\Temp\DeleteMe",
	[string]$Days = 3
)
If (-Not (Test-Path -Path $Path)) {
	"Path '$Path' not found!" | Write-Error
	Exit 1
}
Get-ChildItem $Path -Recurse |
	? {-Not $_.PsIsContainer -And ($_.LastWriteTime -lt (Get-Date).AddDays(-$Days))} |
	Remove-Item

End

Open in new window

LVL 9
stressedout2004Asked:
Who is Participating?
 
Bill PrewCommented:
How about this?

[CmdletBinding(SupportsShouldProcess=$True)]
Param(
	[string]$Path = "C:\Temp\DeleteMe",
	[string]$Dest = "\\server\share\folder",
	[string]$Days = 3
)
If (-Not (Test-Path -Path $Path)) {
	"Path '$Path' not found!" | Write-Error
	Exit 1
}
Get-ChildItem $Path -Recurse |
	? {-Not $_.PsIsContainer -And ($_.LastWriteTime -lt (Get-Date).AddDays(-$Days))} |
	Move-Item -dest $Dest

End

Open in new window

~bp
0
 
becraigCommented:
Param(
      [string]$Path = "C:\Temp\DeleteMe",
      [string]$Days = 3
)
If (!(Test-Path -Path $Path)) {
      "Path '$Path' not found!" 
	exit;
}
else 
{
gci $Path -recurse | ? {!($_.psiscontainer) -and $_.LastWriteTime -lt (Get-date).AddDays(-$days)} | Remove-Item
}

Open in new window

0
 
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
Bill's mod should work (becraig didn't really change anything), but it is better to have the date calculation done once only:
[CmdletBinding(SupportsShouldProcess=$True)]
Param(
  [string]$Path = "C:\Temp\DeleteMe",
  [string]$Dest = "\\server\share\folder",
  [string]$Days = 3
)
If (-Not (Test-Path -Path $Path)) {
  "Path '$Path' not found!" | Write-Error
  Exit 1
}
$thePast = (Get-Date).AddDays(-$Days)
Get-ChildItem $Path -Recurse |
  ? { !$_.PsIsContainer -and $_.LastWriteTime -lt $thePast } |
  Move-Item -dest $Dest

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.