Double post
Need help with powershell script to delete old .bak file
Hi,
I am using PS to copy the latest .bak file from a network location to a local disk. I want that previous day's .bak must get deleted or overridden.
I have tried the below script but it does not work. Please help!!
# specify the network location and file pattern
$source = "\networkpath*.bak"
# specify the destination folder
$destination = "localdisk"
# get the latest .bak file from the network location
$latest = Get-ChildItem $source | Sort-Object LastWriteTime -Descending | Select-Object -First 1
# copy the file to the destination folder, replacing the existing file if it exists
Copy-Item -Path $latest.FullName -Destination $destination -Verbose -Force
# delete old .bak
Get-ChildItem localdisk* -Include *.bak | Where-Object { $_.LastWriteTime -le (Get-Date).AddDays(-1) } |
ForEach-Object { Remove-Item $_ } |
I have tried to use the delete command at the beginning of the script but that did not work either.
3 answers
Sort by: Most helpful
-
Deleted
This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.
Comments have been turned off. Learn more
-
-
MotoX80 35,621 Reputation points
2023-02-24T13:57:51.08+00:00 I have tried the below script but it does not work.
What error did you get? Does the script see the files on localdisk*?
Add troubleshooting statements to display what the script sees. Be sure to include a trailing asterisk on the path.
$bakFiles = Get-ChildItem c:\temp\* -Include *.bak | Where-Object { $_.LastWriteTime -le (Get-Date).AddDays(-1) } "We found {0} bak files to delete." -f $bakFiles.count $bakFiles | ForEach-Object { "Deleting {0}" -f $_.FullName Remove-Item $_ -whatif }