簡體   English   中英

在不通過 Powershell 提示用戶的情況下遞歸刪除文件夾中的文件

[英]Recursively deleting files within folders without prompting the user via Powershell

我目前正在嘗試刪除名為Local的文件夾中的所有文件。 下面的腳本執行此操作,但它會在 PowerShell 窗口中提示用戶。 如果我附加-Force標志我的腳本然后刪除所有文件夾中的所有文件。 我不確定如何刪除本地文件夾中的所有文件而不提示用戶。 下面是有問題的腳本。

$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

您可以首先遞歸搜索要從中刪除文件的目錄,然后對每個目錄中的文件進行非遞歸刪除。

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 }
}

編輯使用FullName目錄中搜索文件時

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 }
}

.FullName附加到您建議的代碼的第五行實際上解決了我的問題。 謝謝拉特金幫助我!

您也可以使用 .NET Delete() 函數,它不要求確認:

$Path = "C:\folder"
$exclude = "file1.txt","file2.txt"

Get-ChildItem -Path $Path -Include * -Exclude $exclude -Recurse | foreach {
    $_.Delete()
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM