查找具有两种特定文件类型的目录并忽略子目录

时间:2018-03-05 19:02:07

标签: powershell

我的任务涉及查找包含两种特定文件类型的目录。参数是我用PowerShell完成的,我只复制其中一个文件类型及其上面的目录结构,并忽略所有子目录。这是目录的样子......

├─ A
│  └─ A1
│     └─ A12
│        ├─ A123
│        │  ├─ working
│        │  └─ working_last
│        ├─ A123.txt
│        ├─ A123.log
│        └─ A123.properies
├─ B
│  └─ B1
│     └─ B12
│        ├─ B123
│        │  └─ working
│        │     └─ working_last
│        └─ B123.properies
└─ C
   └─ C1
      ├─ C1.txt
      └─ C1.log

所以从这个结构来看,我只想复制.log文件(及其上面的目录结构),只要该目录还包含同一级别的.txt文件而忽略所有子目录。我希望我复制的输出看起来像这样:

├─ A
│  └─ A1
│     └─ A12
│        └─ A123.log
└─ C
   └─ C1
      └─ C1.log

我尝试过搜索答案,但我不确定是否输入了正确的搜索字词来寻找答案。

这是我试图用我必须满足的标准确定目录列表。

Get-ChildItem -Path "E:\" -Recurse -Exclude "working","working_last" |
    Where-Object { $_.Extension -match ".log" -and $_.Extension -match ".txt" }

1 个答案:

答案 0 :(得分:0)

枚举源文件夹树中的日志文件,检查它们是否附带一个具有相同基本名称和扩展名.txt的文件,在目标文件夹中创建相对路径,然后复制该文件。

$srcdir = 'E:\'
$dstdir = 'F:\'

Get-ChildItem -Path $srcdir -Filter '*.log' -Recurse | Where-Object {
    # Construct the path for the text file, then check if that file actually
    # exists.
    $txtfile = Join-Path $_.DirectoryName ($_.BaseName + '.txt')
    Test-Path -LiteralPath $txtfile
} | ForEach-Object {
    # At this point we have only log files that do have a matching .txt file.

    # Remove the source directory from the directory path of the file to get the
    # relative path. Prepend that with the destination folder to get the target
    # directory for the file.
    $relpath = $_.DirectoryName.Replace($srcdir, '')
    $abspath = Join-Path $dstdir $relpath

    # Create the directory (silently continues if the directory already exists).
    New-Item -Type Directory -Path $abspath

    # Copy the file to the target folder.
    Copy-Item $_.FullName -Destination $abspath
}