Home > Enterprise >  write a power shell script to maintain latest 5 releases and deleting all other timestamp releases i
write a power shell script to maintain latest 5 releases and deleting all other timestamp releases i

Time:10-21

$path = "D:\ProfileServiceQAT"

$Temp = "D:\\temp1"

$limit = (Get-Date).Adddays(-5)

$Folder = Get-ChildItem  $path | Where {$_.PSIsContainer} | Sort CreationTime -Descending | Select -First 5


$Folder | Copy-Item -Destination $Temp

Remove-Item   $path\* -Recurse

Move-Item $Temp\* -Destination $path

Remove-Item $Temp\* -Recurse

In this above script whenever I run this script, I am only getting empty timestamp releases into temp and then into the path without contents. Please let me know where it going wrong

CodePudding user response:

Try the below code and mark it answer, if it helps you

$path = "D:\ProfileServiceQAT"

$Temp = "D:\temp1"

$limit = (Get-Date).Adddays(-5)

$Folder = Get-ChildItem  $path | Sort CreationTime -Descending|Where {$_.LastWriteTime -ge $limit}

$Folder | Remove-Item -Recurse -Force

CodePudding user response:

As mentioned in the comments, you need to specify the -Recurse switch when you want to copy the whole directory structure with contents - otherwise it just creates the copy of the directory itself, nothing below it.

$Folder | Copy-Item -Destination $Temp -Recurse
  • Related