Powershell script to move old logs

73 Views Asked by At

I have a task to move old logs to new directory automatically. I have a script, but i have small problem about sub directories The source is "D:\3cx". Inside the source, there is some subfolders, like extension numbers. Whenever each extension number gets new calls, new log files are created. So, sub folder's lastmodified date is changing daily. I need that script to mirror two directories (source and destinations). At first, script works fine. But new files are added to the source, and when I run script again, it creates directories again.

Can u help me modify?

#Set source and destination paths

$sourcePath = "D:\\3cx"
$destinationPath = "D:\\3cxnew"

#Create destination directory if it doesn't exist

if (-not (Test-Path -Path $destinationPath)) {
    New-Item -ItemType Directory -Path $destinationPath | Out-Null
}

#Copy contents of source to destination
Get-ChildItem -Path $sourcePath\* | ForEach-Object {
    $destinationFile = Join-Path $destinationPath $_.Name
    Copy-Item -Path $_.FullName -Destination $destinationFile -Recurse -Force
}
Write-Host "Files and folders copied successfully from $sourcePath to $destinationPath."

$limit = (Get-Date).AddDays(-180)
#Delete files older than the $limit.
Get-ChildItem -Path $sourcePath -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.LastWriteTime -lt $limit } | Remove-Item -Force

#Delete any empty directories left behind after deleting the old files.
Get-ChildItem -Path $sourcePath -Recurse -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse

At first, script works fine. But new files are added to the source, and when I run script again, it creates directories again.

0

There are 0 best solutions below