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
Olaf
March 26, 2021, 9:32pm
2
First of all - please format your code as code. There are charachters missing.
Here you can read how that works: Guide to Posting Code.
Discourse uses Markdown for text formatting. There is a reference sheet and quick tutorial here: Markdown Reference
You can produce in-line code formatting by wrapping your code in backticks (`). For example, `Get-ChildItem` produces Get-ChildItem.
For larger code blocks, place a line containing three backticks above and below your code. For example
```
# 256-Color Foreground & Background Charts
echo “`n$esc[1;4m256-Color Foreground & Background Charts$esc[0m”
foreach ($fgbg in 38,48) { #…
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 .
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;
Olaf
March 27, 2021, 7:18am
5
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. Much prefer the one liner over my more complex method of doing it.