Move files with specific date using Powershell Get-ChildItem - powershell

Need some help with a powershell script.
I need to move files by a specific last modified date with similar names.
Here is the script I tried running and it just hangs...
$SourceFolder = "C:\documents\testing123.txt"
$targetFolder = "D:\documents"
Get-ChildItem -Path $SourceFolder -Filter E0100* | where-object {$_.LastWriteTime -eq ("08/01/2015") | move-item -destination $targetFolder

Since, LastWriteTime is a DateTime the -ge in comparing an exact time. Here is an example that copies using a date range that I believe you desire.
$SourceFolder = "C:\documents\testing123.txt"
$targetFolder = "D:\documents"
$startTime =[DateTime]"08/01/2015"
$endTime = $startTime.AddDays(1)
Get-ChildItem -Path $SourceFolder -Filter E0100* |
Where-Object {$_.LastWriteTime -ge $startTime -and $_.LastWriteTime -lt $endTime} |
Move-Item -destination $targetFolder
As others have mentioned, the source folder path seems incorrect.
Here is a robocopy version of the script I tried (date, paths, and filter have been changed)
$SourceFolder = "D:\test"
$targetFolder = "D:\test2"
$startTime =[DateTime]"01/05/2017"
$endTime = $startTime.AddDays(1)
$files = #()
Get-ChildItem -Path $SourceFolder -Filter * |
Where-Object {$_.LastWriteTime -ge $startTime -and $_.LastWriteTime -lt $endTime -and $_.Attributes -ne 'Directory'} |
ForEach-Object { $files += $_.Name}
if($files.Count -gt 0)
{
Write-Verbose "running robocopy $SourceFolder $targetFolder $files /mov" -Verbose
robocopy $SourceFolder $targetFolder $files /mov
}

This is a simple two-line PowerShell that will get move your files by date and file type. You can change the Move-Item to Copy-Item if you do not want to move them.
$Now=Get-Date
Get-ChildItem E:\scripts\logs\*.txt | Where-Object { $_.LastWriteTime -lt $Now.AddDays(-7) } | Move-Item -Destination E:\scripts\logs\Archive\7Days

Related

moving files to multiple folders and zipping using powershell

I have requirement of moving files older than 7 days from a folder in to a sub folder and zip them and delete from source location.
folder structures are like. ( Files generate on these folders on daily basis)
C:\Users\529817\TEST\Country1
C:\Users\529817\TEST\Country2
C:\Users\529817\TEST\Country3
I need move them to a subfoldes inside and zip them and delete from source location.
C:\Users\529817\TEST\Country1\Archive
C:\Users\529817\TEST\Country2\Archive
C:\Users\529817\TEST\Country3\Archive
This is one interface. Like this i have 8 more interfaces which have files inside for different countries. The smae way of archiving older than 7 days need to be done for all 8 interfaces or main folders.
I just tried below code and it worked for me.
1.
$SourcePath = "C:\Users\529817\TEST\Country1"
$TargetPath = "C:\Users\529817\TEST\Country1\ARCHIVE"
$YourDirToCompress ="C:\Users\529817\TEST\Country1\ARCHIVE"
$SourcePath_1 = "C:\Users\529817\TEST\Country2"
$TargetPath_1 = "C:\Users\529817\TEST\Country2\ARCHIVE"
$YourDirToCompress_1 ="C:\Users\529817\TEST\Country2\ARCHIVE"
$SourcePath_2 = "C:\Users\529817\TEST\Country3"
$TargetPath_2 = "C:\Users\529817\TEST\Country3\ARCHIVE"
$YourDirToCompress_2 ="C:\Users\529817\TEST\Country3\ARCHIVE"
$Days = "7"
$Date = Get-Date -format yyyy-MM-dd_HH-mm
Write-Verbose $Activity
Get-Childitem -recurse -Path $SourcePath | Where-Object {$_.LastWriteTime -lt (get-date).AddDays(-$days)} | Compress-Archive -DestinationPath $YourDirToCompress\$date.zip -update
Get-ChildItem -Recurse -Path $SourcePath -Force | Where-Object {$_.LastWriteTime -lt (get-date).AddDays(-$days)} | Remove-Item -Force
Write-Verbose $Activity
Get-Childitem -recurse -Path $SourcePath_1 | Where-Object {$_.LastWriteTime -lt (get-date).AddDays(-$days)} | Compress-Archive -DestinationPath $YourDirToCompress_1\$date.zip -update
Get-ChildItem -Recurse -Path $SourcePath_1 -Force | Where-Object {$_.LastWriteTime -lt (get-date).AddDays(-$days)} | Remove-Item -Force
Write-Verbose $Activity
Get-Childitem -recurse -Path $SourcePath_2 | Where-Object {$_.LastWriteTime -lt (get-date).AddDays(-$days)} | Compress-Archive -DestinationPath $YourDirToCompress_2\$date.zip -update
Get-ChildItem -Recurse -Path $SourcePath_2 -Force | Where-Object {$_.LastWriteTime -lt (get-date).AddDays(-$days)} | Remove-Item -Force
Can somebody tell me if a loop can be written to do archive above 3 subfolders instead of writing the compress-archive and delete command line 3 times.
I loop is possible then please let me know whether 8 different scripts need to be written for 8 interfaces or with a single script it can handle all 8 interfaces and its subfolders??
I appreciate the help...
one possibility :
$AllDir=#(
#('C:\Users\529817\TEST\Country1', 'C:\Users\529817\TEST\Country1\ARCHIVE'),
#('C:\Users\529817\TEST\Country2', 'C:\Users\529817\TEST\Country2\ARCHIVE'),
#('C:\Users\529817\TEST\Country3', 'C:\Users\529817\TEST\Country3\ARCHIVE')
)
$Days = "7"
$Date = Get-Date -format yyyy-MM-dd_HH-mm
$MaxDate =(get-date).AddDays(-$days)
$AllDir | %{
$SourcePath=$_[0]
$YourDirToCompress=$_[1]
Get-Childitem -recurse -Path $SourcePath | Where LastWriteTime -lt $MaxDate | Compress-Archive -DestinationPath $YourDirToCompress\$date.zip -update
Get-ChildItem -Recurse -Path $SourcePath | Where LastWriteTime -lt $MaxDate | Remove-Item -Force
}
If you want a generic method :
#take all country directory
$AllDirCountry=Get-ChildItem "C:\Users\529817\TEST\Country*" -directory
$Days = 7
$Date = Get-Date -format yyyy-MM-dd_HH-mm-ss-fffff
$MaxDate =(get-date).AddDays(-$days)
$AllDirCountry | %{
#build path
$SourcePath=$_.FullName
$YourDirToCompress="{0}\ARCHIVE" -f $_.FullName
$ArchiveDay="{0}\{1}" -f $YourDirToCompress, $Date
$ZipFile="{0}\{1}.zip" -f $YourDirToCompress, $Date
#remove archive day
Remove-Item $ArchiveDay -Recurse -Force -ErrorAction SilentlyContinue
#create archive directory if not exists
New-Item $YourDirToCompress -ItemType Directory -Force
#create archive of day directory if not exists
New-Item $ArchiveDay -ItemType Directory -Force
#move directory and file except files into archive directory
Get-Childitem -recurse -Path $SourcePath | Where {$_.LastWriteTime -lt $MaxDate -and $_.Directory -notlike "$YourDirToCompress*"} | move-Item -Destination $ArchiveDay -ErrorAction SilentlyContinue
#compress archive day
Compress-Archive "$ArchiveDay" -DestinationPath $ZipFile
#remove archive day
Remove-Item $ArchiveDay -Recurse -Force -ErrorAction SilentlyContinue
}

Powershell compress files older than X days from folder path by keeping folder structure (folder + sub-folders) and also exclude a few sub-folders

I'm pretty new to Powershell in general, I've come across some partial solutions, but I can't find the right fit.
Ideally I would like to Archive (Zip) with Powershell but only files of a certain age (x days/months), but I would prefer keeping the folder structure and also add exclusions.
Here's what I've been trying to use (without success):
$inputFolder = "C:\Temp\Test"
$excludeFolders = #("\subfolderToKeep")
$ouputFileName="C:\Temp\archive.zip"
$Daysback = "-5"
$CurrentDate = Get-Date
$DatetoDelete = $CurrentDate.AddDays($Daysback)
$tempFolder = [System.IO.Path]::GetTempFileName()
Remove-Item $tempFolder -Force
New-Item -Type Directory -Path $tempFolder -Force
$exclude =#()
$excludeFolders | ForEach-Object {
$exclude+=(Join-Path $inputFolder $_)
Get-ChildItem (Join-Path $inputFolder $_) -Recurse |
ForEach-Object{$exclude+=$_.FullName}}
Get-ChildItem $inputFolder -Recurse | Where-Object { $_.FullName -notin $exclude -and $_.LastWriteTime -lt $DatetoDelete } |
Copy-Item -Destination {Join-Path $tempFolder $_.FullName.Substring($inputFolder.length)}
Get-ChildItem $tempFolder |
Compress-Archive -DestinationPath $ouputFileName -Update
The current setup would work without the date filtering:
-and $_.LastWriteTime -lt $DatetoDelete

Issue with Copying files from and too within certain dates in Powershell

I am new to power shell, I am trying to copy files from one location to another between specific dates.
I have an issue with the dates part it seems to be copying all the files regardless of the dates, any idea why?
$StartDate = (Get-date).Addyears(-2)
$EndDate = (Get-date).Adddays(-2)
$src = "C:\Sites\T\Test01"
$dst = "C:\Customer\"
Get-ChildItem $src -exclude "Aeromark" -Recurse | Copy-Item -Destination $dst -Force |
Where-Object {($_.LastWriteTime.Date -ge $StartDate.Date) -and ($_.LastWriteTime.Date -le $EndDate.Date)}
Where-Object needs to go before Copy-Item in your particular case. The Copy-Item command is being called before Where-Object excludes the files based on date.
Here is your code re-arranged:
Get-ChildItem $src -exclude "Aeromark" -Recurse |
Where-Object {($_.LastWriteTime.Date -ge $StartDate.Date) -and ($_.LastWriteTime.Date -le $EndDate.Date)} |
Copy-Item -Destination $dst -Force

Powershell delete Folder if all Files older than x days

I'm new at PowerShell and don't know so much about it.
I'm searching for a way to delete a folder and all sub-folders if all files in this are older than x days. I have an code to delete all files in a folder and all sub-folders but I don't know how to change it right.
$Now = Get-Date
$Days = "30"
$TargetFolder = "C:\temp"
$Extension = "*.*"
$LastWrite = $Now.AddDays(-$Days)
$Files = Get-Childitem $TargetFolder -Include $Extension -Recurse | Where {($_.CreationTime -le "$LastWrite") -and ($_.LastWriteTime -le "$LastWrite")}
foreach ($File in $Files)
{
if ($File -ne $NULL)
{
write-host "Deleting File $File" -ForegroundColor "Red"
Remove-Item $Location.FullName | out-Null
}
else
{
Write-Host "No more files to delete!" -foregroundcolor "Green"
}
}
Enumerate all folders and sort them longest path first, so you process the directories bottom to top:
Get-ChildItem $TargetFolder -Recurse -Directory |
Select-Object -Expand FullName |
Sort-Object Length -Desc
Filter the list for directories that don't have any file or folder newer than x days in them:
... | Where-Object {
-not $(Get-ChildItem $_ -Recurse | Where-Object {
$_.Creationtime -ge $LastWrite -or
$_.LastWriteTime -ge $LastWrite
})
}
Then remove the resulting folders:
... | Remove-Item -Recurse -Force

Delete files older than 15 days using PowerShell

I would like to delete only the files that were created more than 15 days ago in a particular folder. How could I do this using PowerShell?
The given answers will only delete files (which admittedly is what is in the title of this post), but here's some code that will first delete all of the files older than 15 days, and then recursively delete any empty directories that may have been left behind. My code also uses the -Force option to delete hidden and read-only files as well. Also, I chose to not use aliases as the OP is new to PowerShell and may not understand what gci, ?, %, etc. are.
$limit = (Get-Date).AddDays(-15)
$path = "C:\Some\Path"
# Delete files older than the $limit.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force
# Delete any empty directories left behind after deleting the old files.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse
And of course if you want to see what files/folders will be deleted before actually deleting them, you can just add the -WhatIf switch to the Remove-Item cmdlet call at the end of both lines.
If you only want to delete files that haven't been updated in 15 days, vs. created 15 days ago, then you can use $_.LastWriteTime instead of $_.CreationTime.
The code shown here is PowerShell v2.0 compatible, but I also show this code and the faster PowerShell v3.0 code as handy reusable functions on my blog.
just simply (PowerShell V5)
Get-ChildItem "C:\temp" -Recurse -File | Where CreationTime -lt (Get-Date).AddDays(-15) | Remove-Item -Force
Another way is to subtract 15 days from the current date and compare CreationTime against that value:
$root = 'C:\root\folder'
$limit = (Get-Date).AddDays(-15)
Get-ChildItem $root -Recurse | ? {
-not $_.PSIsContainer -and $_.CreationTime -lt $limit
} | Remove-Item
Basically, you iterate over files under the given path, subtract the CreationTime of each file found from the current time, and compare against the Days property of the result. The -WhatIf switch will tell you what will happen without actually deleting the files (which files will be deleted), remove the switch to actually delete the files:
$old = 15
$now = Get-Date
Get-ChildItem $path -Recurse |
Where-Object {-not $_.PSIsContainer -and $now.Subtract($_.CreationTime).Days -gt $old } |
Remove-Item -WhatIf
Try this:
dir C:\PURGE -recurse |
where { ((get-date)-$_.creationTime).days -gt 15 } |
remove-item -force
Esperento57's script doesn't work in older PowerShell versions. This example does:
Get-ChildItem -Path "C:\temp" -Recurse -force -ErrorAction SilentlyContinue | where {($_.LastwriteTime -lt (Get-Date).AddDays(-15) ) -and (! $_.PSIsContainer)} | select name| Remove-Item -Verbose -Force -Recurse -ErrorAction SilentlyContinue
If you are having problems with the above examples on a Windows 10 box, try replacing .CreationTime with .LastwriteTime. This worked for me.
dir C:\locationOfFiles -ErrorAction SilentlyContinue | Where { ((Get-Date)-$_.LastWriteTime).days -gt 15 } | Remove-Item -Force
Another alternative (15. gets typed to [timespan] automatically):
ls -file | where { (get-date) - $_.creationtime -gt 15. } | Remove-Item -Verbose
#----- Define parameters -----#
#----- Get current date ----#
$Now = Get-Date
$Days = "15" #----- define amount of days ----#
$Targetfolder = "C:\Logs" #----- define folder where files are located ----#
$Extension = "*.log" #----- define extension ----#
$Lastwrite = $Now.AddDays(-$Days)
#----- Get files based on lastwrite filter and specified folder ---#
$Files = Get-Childitem $Targetfolder -include $Extension -Recurse | where {$_.LastwriteTime -le "$Lastwrite"}
foreach ($File in $Files)
{
if ($File -ne $Null)
{
write-host "Deleting File $File" backgroundcolor "DarkRed"
Remove-item $File.Fullname | out-null
}
else {
write-host "No more files to delete" -forgroundcolor "Green"
}
}
$limit = (Get-Date).AddDays(-15)
$path = "C:\Some\Path"
# Delete files older than the $limit.
Get-ChildItem -Path $path -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force -Recurse
This will delete old folders and it content.
The following code will delete files older than 15 days in a folder.
$Path = 'C:\Temp'
$Daysback = "-15"
$CurrentDate = Get-Date
$DatetoDelete = $CurrentDate.AddDays($Daysback)
Get-ChildItem $Path -Recurse | Where-Object { $_.LastWriteTime -lt $DatetoDelete } | Remove-Item