Unable to delete old .bak files

Hello Forum,

 

Im using the following commands in powerGUI and it works intermittently and when used in SQL Agent is never works , this is the first step to delete old backups before creating the new ones.

I have tried both scripts but nothing works ..

 

1.Get-ChildItem $BakLoc -recurse -include *.bak |Remove-Item -force -recurse -ErrorAction SilentlyContinue

 

 2. foreach($file in $BakLoc)

   {

      $FilePath = $file.fullname

 IF((Test-Path $FilePath) -eq $True){remove-item -Literalpath $FilePath -ErrorAction SilentlyContinue}

   }

  • Please post your error message. "Nothing works" doesn't give us anything to go on.
  • This could easily be a permissions issue but since you turned off errors you'll never know. Don't use -ErrorAction SilentlyContinue. This is what we did in the days of VBScript with OnErrorResumeNext.  In PowerShell learn how to trap and handle errors. And in your case without the error message you'll have no clue about how to fix your problem.

  • CategoryInfo          : ObjectNotFound: (\\...60226212108.bak:String) [Remove-Item], ItemNotFoundException

    FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand

     

    Deleting File \\........._20160226215208.bak

    Remove-Item : Cannot find path '\\....20160226215208.bak' because it does not exist.

    At \Cleanup Old  Backups.ps1:35 char:9

    +         Remove-Item $File.FullName | out-null

    +         ~~~~~~~~~~~~~~~~~~~~~~~~~~

        + CategoryInfo          : ObjectNotFound: (\\...60226215208.bak:String) [Remove-Item], ItemNotFoundException

        + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand

  • Get out of PowerGUI and work right in the PowerShell console. That eliminates any quirks that PowerGUI might be adding.  You should be able to define a variable for your backup location

    $BakLoc = "C:\work"

    Then run a command like this:

    dir $bakloc -include *.bak -recurse | del -whatif

    You should see all the files that PowerShell would delete.

  • And if you go the second route, don't use -LiteralPath. Use -Path. Unless your full path contains characters that PowerShell might misinterpret.

  • thnx Jeff , will try and get back