Need help with powershell script to delete old .bak file

Sajid Shaikh 0 Reputation points
2023-02-24T07:03:30.35+00:00

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.

PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,864 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. 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

  2. Limitless Technology 44,666 Reputation points
    2023-02-24T13:57:04.3466667+00:00

    Double post


  3. 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
    } 
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.