簡體   English   中英

如何從多個文件夾中刪除文件,不包括幾個文件夾?

[英]How to delete files from multiple folders excluding couple of folders?

我們有一種情況,cp.exe 和 cp.dll 被復制到所有文件夾的構建工件中,我們希望它們只成為 PS.Manager.Service 和 PS.A.Service 文件夾/工件的一部分。

從其余所有文件夾中,必須刪除 cp.exe 及其 cp.dll。 我嘗試使用以下腳本執行此操作,但它不起作用。 我不確定我在這里錯過了什么。

任何建議都會有幫助。

謝謝。

$SourceDirectory = "e:\cache\Agent03\2\s"
$EXcludeManagerFolder = "e:\cache\Agent03\2\s\PS.Manager.Service"
$EXcludeAFolder = "e:\cache\Agent03\2\s\PS.A.Service"

gci -path "$SourceDirectory" -Include "cp.exe, cp.dll" -Exclude "$EXcludeManagerFolder","$EXcludeAFolder " -Recurse -Force | Remove-Item -Recurse -Force

正如zett42已經評論的那樣, IncludeExclude (以及Filter )僅適用於對象名稱,而不是完整路徑。

最簡單的方法是使用您需要排除的文件夾創建一個正則表達式字符串,以便您可以匹配(或-notmatch在這種情況下)

$SourceDirectory = "e:\cache\Agent03\2\s"
# create a regex of the files and/or folders to exclude
$exclude = 'PS.Manager.Service', 'PS.A.Service'  # foldernames to exclude
# each item will be Regex Escaped and joined together with the OR symbol '|'
$notThese = ($exclude | ForEach-Object { [Regex]::Escape($_) }) -join '|'

(Get-ChildItem -Path $SourceDirectory -Include 'cp.exe', 'cp.dll' -File -Recurse).FullName |
    Where-Object { $_ -notmatch $notThese } |
    Remove-Item -Force

暫無
暫無

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

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