首页 > 解决方案 > Powershell - 获取最后修改文件的父目录名称

问题描述

我有几个文件夹,它们里面都有一个 Log 文件夹和日志文件。只有一个文件夹会修改其日志文件。我需要检索它的顶级父目录名称。

我不能使用Sort-Object LastWriteTime,因为每当更新日志时 - 只有日志文件更新其最后修改时间。theLog和 thetop parent folder根本没有lastwritetime更新。

我怎样才能做到这一点?

Folder1\Log\filename1.log
Folder2\Log\filename3.log -> Assume this is the latest one that got its log file updated.
Folder3\Log\filename5.log
Folder4\Log\filename2.log
Folder5\Log\filename6.log

我想获得“Folder2”作为输出

标签: powershell

解决方案


您可以使用Get-ChildItem, 过滤 '*.log' 文件并通过子文件夹所在的根文件夹递归执行此操作。

然后对文件 LastWriteTime 属性进行排序,选择最新的并从中获取文件夹名称:

$rootFolder = 'X:\TheRootFolderWhereTheSubFoldersAre'
Split-Path -Path ((Get-ChildItem -Path $rootFolder -Filter '*.log' -File -Recurse | 
                   Sort-Object LastWriteTime | Select-Object -Last 1).DirectoryName) -Leaf

推荐阅读