繁体   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