Reputation:
I'm currently trying to remove all the files within a folder named Local. The script below does this, but it prompts the user in a PowerShell window. If I append the -Force
flag my script then removes all files within all folders. I'm not sure how to remove all the files within the Local folder and not prompt the user. Below is the script in question.
$Path = "C:\Program Files (x86)\folder1\folder2\"
Function Clear-Cache
{
Get-ChildItem 'C:\Users\Admin\Documents\GI Studies' -File -Recurse | Where-Object {$_.FullName -match "data\\local"} | % {del $_.FullName #-Force}
}
Clear-Cache
Upvotes: 0
Views: 3700
Reputation: 608
You can also use .NET Delete() function, it does not ask for confirmation:
$Path = "C:\folder"
$exclude = "file1.txt","file2.txt"
Get-ChildItem -Path $Path -Include * -Exclude $exclude -Recurse | foreach {
$_.Delete()
}
Upvotes: 0
Reputation: 16792
You could first do a recursive search for the directory(ies) from which to delete files, then do a non-recursive delete of the files in each of those.
Function Clear-Cache
{
$localFolders = Get-ChildItem 'C:\Users\Admin\Documents\GI Studies' -Directory -Recurse | Where-Object {$_.FullName -match 'data\\local$'}
$localFolders |% { dir $_.FullName -File | del -Force }
}
Edit
Use FullName
of directory when searching for files
Upvotes: 3
Reputation:
Function Clear-Cache
{
$localFolders = Get-ChildItem 'C:\Users\Admin\Documents\GI Studies' -Directory -Recurse | Where-Object {$_.FullName -match 'data\\local$'}
$localFolders |% { dir $_.Fullname -File | del -Force }
}
Appending .FullName
to the fifth line of your suggested code actually solved my problem. Thank you latkin for assisting me!
Upvotes: 0