Deleting Files!

Hi

I’m trying to delete a DIRECTORY that I have just crated:

Mode LastWriteTime Length Name


d----- 3/26/2021 12:04 PM 20210210

$Daysback = (Get-Date)

$directories = @(‘\newpenn.local\newpenn\App_Data\Integra\UAT\LPA_TEST*’)

foreach ($i in $directories) {

Get-ChildItem -Path $i -Directory -Recurse -Force | Where-Object { $_.LastWriteTime -eq $Daysback } | Remove-Item -Force

}

The scripts run without any error the Directory is not getting Deleted.

Thanks

First of all - please format your code as code. There are charachters missing.
Here you can read how that works: Guide to Posting Code.

Now - your question:
You create the variable $Daysback with exact date and time of NOW (the moment you run this script). It is pretty much impossible that you have a folder with the exact LastWriteTime from NOW. :wink:
The next thing - if your folder is not empty you will have to add the paramter -Recurse to Remove-Item. Otherwise you will be prompted for confirmation.

1 Like

I had to resort to remove a ‘.git’ folder and it’s sub-folder and files.

  Get-ChildItem -Path $psKBGitPath -Recurse -File | Remove-Item -Recurse -Force
  Start-Sleep -Seconds 1;
  $dirCount = $(Get-ChildItem -Path $psKBGitPath -Recurse -Directory).Count
  While ($dirCount -gt 0) {
    Get-ChildItem -Path $psKBGitPath -Recurse -Directory | Remove-Item -Force -ErrorAction SilentlyContinue
    Start-Sleep -Seconds 2
    $dirCount = $(Get-ChildItem -Path $psKBGitPath -Recurse -Directory).Count
  }
  Remove-Item -Path $psKBGitPath -Force;

The following example removes the .git folder and any sub-folders and files without any prompts appearing.

  Get-ChildItem -Path $psKBGitPath -Recurse -File | Remove-Item -Recurse -Confirm:$false -Force
  Start-Sleep -Seconds 1;
  $dirCount = $(Get-ChildItem -Path $psKBGitPath -Recurse -Directory).Count
  While ($dirCount -gt 0) {
    Get-ChildItem -Path $psKBGitPath -Recurse -Directory | Remove-Item -Recurse -Force -Confirm:$false -ErrorAction SilentlyContinue
    Start-Sleep -Seconds 2
    $dirCount = $(Get-ChildItem -Path $psKBGitPath -Recurse -Directory).Count
  }
  Remove-Item -Path $psKBGitPath -Recurse -Confirm:$false -Force;

To remove a certain folder with its subfolders this is actually all you need:

Remove-Item -Path 'D:\sample\with\subfolders' -Recurse -Force
1 Like

Sorry for the late response. Thank you Olaf and cadayton!

Of course now you tell me. :slight_smile: Much prefer the one liner over my more complex method of doing it.