Powershell只为每个子目录保留一个扩展文件

e0bqpujr  于 2022-12-04  发布在  Shell
关注(0)|答案(1)|浏览(109)

有一个目录C:\New,在该目录中有多个包含文本文件的子目录,如
C:\New\ABC:abc.txt、xyd.txt文件格式
C:\New\XYZ:abc.txt、xyd.txt文件格式
现在,我只想在每个子目录中保留一个随机文本文件,并删除所有其他文本文件。输出
C:\New\ABC:xyd.txt文件


这是一个脚本,它正在工作,但它只工作的第一个文件夹,并删除所有的文本文件从其他子目录。

Get-ChildItem -Path "C:\New" -Recurse -Include *.txt | Select-Object -Skip 1 | Remove-Item
taor4pac

taor4pac1#

你需要把你的代码分成更小的部分,这里有一种方法,基本上首先获取所有的目录,然后为每个目录获取它的文件。然后获取一个随机文件并删除其余文件的方法可以不同,这个方法将所有文件存储在一个ArrayList中,它允许从集合中删除项。

# get all subdirectories
Get-ChildItem -Path "C:\New" -Recurse -Directory | ForEach-Object {
    # get all files of this subdirectory
    [Collections.ArrayList] $files = @($_ | Get-ChildItem -Filter *.txt -File)
    # pick a random file
    $ran = $files | Get-Random
    # remove this file from the list
    $files.Remove($ran)
    # delete the rest
    $files | Remove-Item
}

相关问题