user1739860
user1739860

Reputation:

Recursively deleting files within folders without prompting the user via Powershell

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

Answers (3)

Krzysztof Gapski
Krzysztof Gapski

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

latkin
latkin

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

user1739860
user1739860

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

Related Questions