I'm trying to move all files six months or older into an archive file
I have
#set root folder
$baseFolder = "C:\Users\Caleb\Desktop"
$archiveBase = "C:\Users\Caleb\Desktop"
$limit_to=(Get-date (Get-date -Format d)).AddDays(-180)
#get files inside root
$folder = Get-ChildItem $baseFolder -File
#for each folder
foreach($file in Where-$folder.CreationTime -lt $limit_to ) {
#build the move destination path
$a=$file.CreationTime.Date.Year
$archive="Archive"
$name=$a+" "+$archive
$destination = Join-Path $archiveBase $name
#Create Directory And Deposite Files
if(Test-Path $destination)
{
mv $file $destination
}
else
{
mkdir $destination
mv $file $destination
}
}
I cant seem to get only the files that are older than 180 days.
I am a beginner so any efficiency changes I could make I'm open to
try this
$baseFolder = "C:\Users\Caleb\Desktop\"
$archiveBase = "C:\Users\Caleb\Desktop\"
$limit_to=(Get-date (Get-date -Format d)).AddMonths(-6)
mkdir $archiveBase -force
Get-ChildItem $baseFolder -File | where CreationTime -lt $limit_to | foreach {move-item $_.FullName -Destination ($archiveBase + $_.CreationTime.Year + " Archive" + $_.Name) -Force }
Related
I have tried below powershell script to move files older than 7 days from Newfolder to Archive_folder. The script is moving the entire path to the Archive_folder (means its creating folders \Users\529817\New folder in to Archive_folder and then copying files and not zipping the folder) , I need help in copying only files from NewFolder to Archive_folder and zip that folder.
$ArchiveYear = "2018"
$ArchiveMonth = "10"
$ArchiveDay = "10"
$SourcePath = "C:\Users\529817\New folder"
$TargetPath = "C:\Users\529817\New folder\Archive_folder"
$YourDirToCompress = "C:\Users\529817\New folder"
$ZipFileResult = "C:\Users\529817\New folder\Archive_folder\$ArchiveDay$ArchiveMonth.zip"
Get-ChildItem $YourDirToCompress -Directory |
#where { $_.Name -notin $DirToExclude} |
Compress-Archive -DestinationPath $ZipFileResult -Update
$Days = "7"
$LogPath = "C:Users\529817\Temp"
$Date = Get-Date -format yyyy-MM-dd_HH-mm
$TargetFolder = "$TargetPath\$Date"
$LogFile = "$LogPath\ArchiveLog-$date.txt"
$TargetZipFile = "$TargetPath\$Date.zip"
$Activity = "Move files older than $Days days from $SourcePath to $TargetFolder"
Write-Verbose $Activity
$OldFiles = Get-Childitem -Path $SourcePath -recurse | Where-Object {$_.LastWriteTime -lt (get-date).AddDays( - $days)}
$Total = $Oldfiles.Count
$Current = 0
$OldFiles | ForEach {
$Current ++
$Filename = $_.fullname
Write-Progress -Activity $Activity -Status $FileName -PercentComplete ($Current / $Total * 100)
$Split = $FileName -split '\\'
$DestFile = $split[1..($split.Length - 1)] -join '\'
$DestFile = "$TargetFolder\$DestFile"
Try {
$null = New-Item -Path $DestFile -Type File -Force
$Null = Move-Item -Path $FileName -Destination $DestFile -Force -ErrorAction:SilentlyContinue
"Successfully moved $filename to $targetfolder" | add-content $LogFile
}
Catch {
$Err = $_.Exception.Message
Write-Error $Err
"Error moving $filename`: $Err " | add-content $LogFile
}
}
You have two problems here:
Your zip file isn't going where you want it to go
Instead, all of the items which should be in the zip are going where the zip should go.
Let's figure out why this is happening so you can do what you need to get it working.
Problem 1
You have line 10 which looks like this:
Compress-Archive -DestinationPath $ZipFileResult -Update
This creates the Zip file but you don't actually do anything with this file, as in we don't see this $ZipFileResult used again in the code. This is why your zip file isn't showing up where you want it to be.
Problem 2
The end of this script has this big block where you are expressly copying the files to the directory,right where you don't want them.
Try {
$null = New-Item -Path $DestFile -Type File -Force
$Null = Move-Item -Path $FileName -Destination $DestFile -Force -ErrorAction:SilentlyContinue
"Successfully moved $filename to $targetfolder" | add-content $LogFile
}
If you only want to move the Zip file, then you can shorten this whole script. Delete everything from line 19 and on down, which begins with this line.
$OldFiles = Get-Childitem -Path $SourcePath -recurse | Where-Object {$_.LastWriteTime -lt (get-date).AddDays( - $days)}
And instead, add a Move-Item command to copy that $ZipFileResult file over to whichever directory you want it to go.
Finally, there are a number of lines which don't do anythign and can be deleted, like this line $TargetZipFile = "$TargetPath\$Date.zip"
I am trying to to create an efficient PowerShell script that moves a list of files of .xlsx extension into another folder. About 30 files get generated with the current month and year at the end e.g "- January 2018" into this folder path \otnas6uk\sd.test-it.com$\PROJECTS\
Ideally if the Month and Year could be defined at the start so it loops through all files in the root directory and moves them to the correct folder listed.
This is pseudocode of how I think it could work.
$month = "February"
$year = "2018"
Move-Item -Path "\\otnas6uk\sd.test-it.com$\PROJECTS\\Zentic Report - $month $year.xlsx" -Destination \\zemnas\sd.Zentic-test.com$\Technology\Reports
All files and destinations would be predefined with only the month and year used as a parameter.
#region inputs
$month = 12
$year = 2018
$sourceDirectory = "C:\temp"
$destinationDirectory = "C:\destination"
$fileFilter = "*.xlsx"
#endregion
#region input validation
if (-not (Test-Path -Path $sourceDirectory)) {
throw "Can't find source directory"
}
# Month has to be between 1 and 12
if ($month -lt 1 -or
$month -gt 12
) {
throw "BAD MONTH!"
}
# Recent-ish years only
if ($year -lt ((Get-Date).Year - 1) -or
$year -gt ((Get-Date).Year + 2)
) {
throw "BAD YEAR!"
}
#region
#region destination
# Build up new folder path
$destinationDirectory = Join-Path -Path $destinationDirectory -ChildPath $year
$destinationDirectory = Join-Path -Path $destinationDirectory -ChildPath $month
#Create destination if not exists
if (-not (Test-Path -Path $destinationDirectory)) {
New-Item -Path $destinationDirectory -ItemType Directory | Out-Null
}
#endregion
#region move files
Get-childItem -Path $sourceDirectory -File -Filter $fileFilter |
Move-Item -Destination $destinationDirectory
#engregion
$oldFolder = '\\otnas6uk\sd.test-it.com$\PROJECTS\\Zentic Report'
$jan2018Folder = '\otnas6uk\sd.test-it.com$\PROJECTS'
# Get a list of the files ending with .xlsx
$files = Get-ChildItem $oldFolder | Where { $_.Extension -eq '.xlsx' }
# Move each file over to the new directory
foreach ($file in $files) {
# Repeat if for all months
if ($file.Name -like '*January*' -and $file.Name -like '*2018*') {
$newPath = "$jan2018Folder\$($file.Name)"
}
Move-Item $file $newPath
}
May be this should help move forward:
$Month = "Febuary";
$Year = "2018"
dir .\excelfiles\*$Month*$Year.xlsx|%{move-item -Path $_.FullName -Destination .\Destination.Folder}
Wrote the following code to move files to a specific Year-Month folder on a drive. However, I would also like to zip the folder I wrote to at the end of the operation. How do I do that?
# Get the files which should be moved, without folders
$files = Get-ChildItem 'D:\NTPolling\InBound\Archive' -Recurse | where {!$_.PsIsContainer}
# List Files which will be moved
# $files
# Target Filder where files should be moved to. The script will automatically create a folder for the year and month.
$targetPath = 'D:\SalesXMLBackup'
foreach ($file in $files)
{
# Get year and Month of the file
# I used LastWriteTime since this are synced files and the creation day will be the date when it was synced
$year = $file.LastWriteTime.Year.ToString()
$month = $file.LastWriteTime.Month.ToString()
# Out FileName, year and month
$file.Name
$year
$month
# Set Directory Path
$Directory = $targetPath + "\" + $year + "\" + $month
# Create directory if it doesn't exsist
if (!(Test-Path $Directory))
{
New-Item $directory -type directory
}
# Move File to new location
$file | Move-Item -Destination $Directory
}
The intention is to move these files into a folder and zip them and archive them for later use. So I will schedule this once a month to run for the previous month
If you're using PowerShell v5 then you can use the Compress-Archive function:
Get-ChildItem $targetPath | Compress-Archive -DestinationPath "$targetPath.zip"
This will compress D:\SalesXMLBackup to D:\SalesXMLBackup.zip
This is the code I am using for unzipping all the files in a directory. You just need to modify it enough to zip instead of unzipping.
$ZipReNameExtract = Start-Job {
#Ingoring the directories that a search is not require to check
$ignore = #("Tests\","Old_Tests\")
#Don't include "\" at the end of $loc - it will stop the script from matching first-level subfolders
$Files=gci $NewSource -Fecurse | Where {$_.Extension -Match "zip" -And $_.FullName -Notlike $Ignore}
Foreach ($File in $Files) {
$NewSource = $File.FullName
#Join-Path is a standard Powershell cmdLet
$Destination = Join-Path (Split-Path -parent $File.FullName) $File.BaseName
Write-Host -Fore Green $Destination
#Start-Process needs the path to the exe and then the arguments passed seperately.
Start-Process -FilePath "C:\Program Files\7-Zip\7z.exe" -ArgumentList "x -y -o $NewSource $Destination" -Wait
}
}
Wait-Job $ZipReNameExtract
Receive-Job $ZipReNameExtract
Let me know if it helps.
The UnderDog...
I was hoping someone can help me out with this script which is currently baffling me, I'm not very good at powershell ;)
What I'm trying to achieve is a script that will scan folders and subfolders of my source, looking for *.wav files older than 60 days and then move them to an archive destination, creating a folder structure of \year\month
This is what i've got
$SourceDir = "d:\test"
$DestinationDir = "e:\test"
$files = get-childitem $SourceDir *.wav
foreach ($file in $files)
{
$Directory = $DestinationDir + "" + $file.CreationTime.Date.ToString('yyyy') + "\" + $file.CreationTime.Date.ToString('MM-MMM')
if (!(Test-Path $Directory))
{
New-Item $directory -type directory
}
where-object {$_.LastWriteTime -lt (get-date).AddDays(-61)} | move-item $file.fullname $Directory
}
The script runs without error but doesn't move files :/
--
Following on from Keiths comments below, my script looks as so:
$SourceDir = "d:\test\"
$DestinationDir = "e:\test\"
$date = (get-date).AddDays(-91)
$files = get-childitem -literalpath $SourceDir *.wav
foreach ($file in $files)
{
$Directory = $DestinationDir + "" + $file.CreationTime.Date.ToString('yyyy') + "\" + $file.CreationTime.Date.ToString('MM-MMM')
if (!(Test-Path $Directory))
{
New-Item $directory -type directory
}
if ($file.LastWriteTime -lt $date) {
Write-Host $file
move-item -LiteralPath $file.fullname -Destination $Directory
}
}
And is working perfectly! Thanks Keith
Where-Object is never at the beginning of a pipeline. It requires input to populate the $_ variable you usually use to compare against. Replace that line with:
if ($file.LastWriteTime -lt (get-date).AddMonths(-3)) {
move-item $file.fullname $Directory
}
Although I would compute the date outside the loop:
$date = (get-date).AddMonths(-3)
And use that inside the loop:
...
if ($file.LastWriteTime -lt $date) {
Move-Item -LiteralPath $file.fullname -Destination $Directory
}
...
I want to copy files from A to B in Powershell. For this I want to only copy Files that are older then $days. It works but if I have a Folder with old files and only one file is new, the function doesn't copy the folder with the old files.
Here my code:
function copyFolder($source,$destination,$lastwrite){
foreach($Files in Get-ChildItem $source -Recurse | Where {$_.LastWriteTime -le $lastwrite}){
foreach($File in $Files){
if($File -ne $NULL){
Copy-Item $File.Fullname -Destination $destination -Recurse
}
}
}
}
#Anfangspunkt (A)
$path = "C:\Users\tarasov_w\Downloads"
#Ziel (B)
$destination = "C:\Users\tarasov_w\Desktop\ps_test"
$Now = Get-Date
$Days = 5
$LastWrite = $Now.AddDays(-$Days);
copyFolder -source $path -destination $destination -lastwrite $LastWrite