Copy files 45days old, verify and then delete - powershell

Trying to get a script working that can copy files that are 45 days old to a new network location, verify they copied and then delete those files from the original location. Any help is greatly appreciated

This will get all child items in a folder (Folders and Files) Get-ChildItem Recurse
Select Items older then 45 days $_LastWriteTime -lt (get-date).AddDays(-45)
Move them to a new location move-item -destination
Remove the old items Remove-Item
get-childitem -Path "C:\HERE" -Recurse | where-object {$_.LastWriteTime -lt (get-date).AddDays(-45)} | move-item -destination "\D:\THERE" | Remove-Item
UPDATE 8/12/2017
Added Verify that the file was moved before delete. if(Test-Path $Destination$($_.Name))
$Source = "C:\Source\"
$Destination = "D:\Destination\"
get-childitem -Path "C:\Source\" -Recurse | where-object {$_.LastWriteTime -lt (get-date).AddDays(-45)} | move-item -destination "D:\Destination\" -force | ForEach-Object{
if(Test-Path $Destination$($_.Name)){
Remove-Item $_ -Force
}
}
UPDATE 8/14/2017
All in one line
get-childitem -Path "C:\Source\" -Recurse | where-object {$_.LastWriteTime -lt (get-date).AddDays(-45)} | move-item -destination "D:\Destination\" -force | ForEach-Object{ if(Test-Path $Destination$($_.Name)){Remove-Item $_ -Force}}

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
}

Keep first layer of folders from Get-ChildItem when moving

I am working on some PowerShell script that automatically moves folders and files from the 'X-Drive' folder and move it into the 'Old' folder which also is inside the 'X-Drive' folder, but I want it to keep the first layer folders only, all what's inside can be moved but only the folder needs to be kept, but it also needs to be in the 'Old' folder.
$exclude = #('Keep 1', 'Keep 2')
Get-ChildItem -Path "C:\X-Drive" -Recurse -Exclude $exclude |
Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-0) } |
Move-Item -Destination "C:\X-Drive\Old" -ErrorAction 'SilentlyContinue'
Enumerate the subfolders of C:\X-D_rive, then move their content to corresponding subfolders in C:\X-Drive\old, e.g. like this:
$refdate = (Get-Date).AddDays(-1)
Get-ChildItem 'C:\X-Drive' -Directory -Exclude $exclude | ForEach-Object {
$dst = Join-Path 'C:\X-Drive\old' $_.Name
If (-not (Test-Path -LiteralPath $dst)) {
New-Item -Type Directory -Path $dst | Out-Null
}
Get-ChildItem $_.FullName -Recurse | Where-Object {
$_.LastWriteTime -lt $refdate
} | Move-Item -Destination $dst
}
You may want to add old to $excludes, BTW.
The code assumes you're running PowerShell v3 or newer.

Powershell Cleanup script. Excluded folder not being excluded

I wrote a simple script that will run as a scheduled task every weekend. This script cleans up files older than # days and you can give the name of a folder for exclusion as a parameter. This folder should not be cleaned up by the script. But somehow the script still deletes some files from the excluded folder. But in a strange way no files matching the conditions of the parameter.
For example I run the script to delete files older than 15 days and exclude the folder NOCLEANUP. but some files still get deleted from that folder, but there are still files older than 15 days in the NOCLEANUP folder.
Code below
Thanks in advance and apologies for the dirty code. Still new to PS.
Function CleanDir ($dir, $days, $exclude, $logpath)
{
$Limit = (Get-Date).AddDays(-$days)
$Path = $dir
#Folder to exclude
$ToExclude = $exclude
#Log location
$Log= $logpath
$Testpath = Test-Path -PathType Container -Path $Log
if ($Testpath -ne $true)
{
New-Item -ItemType Directory -Force -Path $Log
}
#Logs deleted files
cd $Log
Get-ChildItem -Path $Path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.LastwriteTime -lt $Limit } | Where-Object { $_.fullname -notmatch $ToExclude} | Where-Object { $_.fullname -notmatch '$RECYCLE.BIN'} | Out-File -FilePath CLEANUPLOG.TXT
# Delete files older than the $Limit.
Get-ChildItem -Path $Path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.LastwriteTime -lt $Limit } | Where-Object { $_.fullname -notlike $ToExclude} | Remove-Item -Force -Recurse
#Goes into every folder separately and deletes all empty subdirectorys without deleting the root folders.
$Folder = Get-ChildItem -Path $Path -Directory
$Folder.fullname | ForEach-Object
{
Get-ChildItem -Path $_ -Recurse -Force | Where-Object {$_.PSIsContainer -eq $True} | Where-Object {$_.GetFiles().Count -eq 0} | Remove-Item -Force -Recurse
}
}

Looping through all subfolders, zipping contents

I'm trying to zip all files in all subdirectories that are older than 31 days.
The following code mainly works, but does some things wrong. It creates new folders and zips them, as desired.
But, it doesn't seem to move the old files into the newly-created directories befoee they are zipped. The line Get-ChildItem -Exclude *.zip | ? {$_.LastWriteTime -lt (Get-date).AddDays(-31) -and -not $_.psIsContainer} | Move-Item -destination $newpath should do that, but doesn't. When I try to run it on its own in the console, it works fine however.
Also, in a tree of folders, this code won't work on the outer edges of the tree. What I mean is that the last folder will not have a new folder created within it.
Does anyone know where I'm going wrong?
function zipfiles ($path,$name){
$date = "$((Get-Date).ToString('yyyy-MM-dd'))"
$newpath = "$path$date"
New-Item -ItemType Directory -Path $newpath
Get-ChildItem -Exclude *.zip | ? {$_.LastWriteTime -lt (Get-date).AddDays(-31) -and -not $_.psIsContainer} | Move-Item -destination $newpath
[Reflection.Assembly]::LoadWithPartialName( "System.IO.Compression.FileSystem" )
$src_folder = $newpath
$destfile = "$newpath.zip"
$compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
$includebasedir = $false
[System.IO.Compression.ZipFile]::CreateFromDirectory($src_folder,$destfile,$compressionLevel, $includebasedir)
Remove-Item $newpath -recurse
}
Get-ChildItem -Recurse -Directory | ForEach-Object { zipfiles($($_.FullName),$($_.Name))}

Delete Folders recently moved to a different directory after 10 days of moving

There is a directory where I am moving folders, from a different directory without any logic(randomly anytime) and these folders needs to be deleted after 10 days of their moving here.
So, will this work? -
$limit = (Get-Date).AddDays(-10)
$path = "C:\Some\Path"
Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force
What I don't know is that this creation time parameter would be updated when I move it to the new directory???
As requested in comments, a solution with renaming folders:
Moving a folder:
$sOldPath = "C:\oldpath\foldertomove" # Change to your actual path
$sNewPath = "C:\newpath" # Change to your actual new path
$sDate = Get-Date -Format "yyyMMdd"
$oFolderToMove = Get-Item -Path $sOldPath
Move-Item -Path $sOldPath -Destination $sNewPath
Rename-Item -Path (Join-Path -Path $sNewPath -ChildPath $oFolderToMove.Name) `
-NewName ("{0}-{1}" -f $sDate, $oFolderToMove.Name)
Resulting path: C:\newpath\yyyyMMdd-foldertomove
Deleting old folders:
$sNewPath = "C:\newpath" # Change to your actual new path
$sDateLimit = ((Get-Date).AddDays(-10)).ToString("yyyyMMdd")
# Assuming that all folders in $sNewPath have date-prefixed names.
Get-ChildItem -Path $sNewPath |
Where-Object { $_.PSIsContainer } |
Foreach-Object {
$sDate = [UInt32]($_.Name.Substring(0,8))
if ($sDate -lt $sDateLimit) {
# Deletes folder and everything in it. Remove -WhatIf switch to execute.
Remove-Item -Path $_.FullName -Recurse -Force -WhatIf
}
}