簡體   English   中英

Powershell:刪除父文件夾名稱不同的文件夾中的文件

[英]Powershell: Delete a file inside a folder with different name of parent folder

我想使用此選項刪除具有特定擴展名(在我的情況下為.cfg)且其文件夾名稱不同的那些文件。 例如,如果我在一個名為MYFOLDER的文件夾中並且在這兩個文件MYFOLDER.cfg和otherfile.cfg中,則應(遞歸)刪除otherfile.cfg。

到目前為止,這就是我所擁有的:

$folder = Get-ChildItem * -exclude *.* -name -recurse
$file = Get-ChildItem * -include *.cfg* -name -recurse | % { [IO.Path]::GetFileNameWithoutExtension($_) }
#$folder | ForEach-Object {Compare-Object $folder $file | <DELETE file with different name>}

我該怎么做最后一行?

提前致謝。 問候。

這將為您做到:

Get-ChildItem -Recurse -Include *.cfg  | % { If ( $_.Name.Split(".")[0] -ne $_.Directory.Name ) {$_.Delete()}}

兩線制,但您可以將其制成單襯板;)

$FolderName = (Get-Location).Path.Split("\")[(Get-Location).Path.Split("\").Count -1]
$Files = Get-ChildItem | Where-Object {$_.Extension -ne ".cfg" -or $_.Name.Split(".")[0] -ne $FolderName} | Remove-Item -Recurse

但是當文件的名稱包含一個點(例如File.Name.cfg)時,此代碼以及Musaab Al-Okaidi的代碼均無法處理

刪除-WhatIf刪除文件:

Get-ChildItem -Filter *.cfg -Recurse | 
Where-Object {$_.BaseName -ne $_.Directory.Name} | 
Remove-Item -WhatIf

暫無
暫無

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

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