I wrote a Powershell script that deletes all files in the subfolders of the current path. It works fine, but it also deletes all files in the current/root folder. How can I exclude that folder?
$CountedFiles = (Get-ChildItem -File -Recurse | Measure-Object).Count
$NewCountedFiles = ($CountedFiles - 1)
$path = Get-Location
Get-ChildItem -Path $path -Include *.* -Exclude *.ps1 -File -Recurse | foreach { $_.Delete()}
Write-Host "Es wurde(n) '$NewCountedFiles' Datei(en) in allen Unterordnern und im derzeitigen Ordner im Pfad: '$path' gelöscht!"
pause
Currently I have it so that it exludes the .ps1 (Powershell Script File) for testing so it doesn't deletes itself.
I tried to find a way to exclude the root folder, but haven't found one since I am new to Powershell. I hope that someone knows an easy why to do so.
If you need to delete the files, but not the subfolders, you can try this:
$files = Get-ChildItem -Path $pwd -File -Recurse
$filesToDelete = $files | Where-Object { $_.Directory.FullName -ne $pwd }
$filesToDelete | Remove-Item -Force
And you delete all the files without remove the root content and the subfolders.