You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PowerShell获取目录树列表及对应文件所有者等元数据信息

实现方案

Windows 环境

直接使用PowerShell即可完成输出,不需要额外安装软件:

  • 基础版本,直接输出所有文件的完整路径+所有者:
Get-ChildItem -Recurse | Select-Object FullName, @{Name='Owner';Expression={(Get-Acl $_.FullName).Owner}} | Format-Table -AutoSize
  • 和你给出的示例格式完全匹配的缩进版本,替换根目录路径后直接运行即可:
$rootPath = "替换为你要扫描的根目录的绝对路径"
function Get-DirTree($path, $indent = 0) {
    $items = Get-ChildItem -Path $path
    foreach ($item in $items) {
        $prefix = ">" + ("    " * $indent)
        if ($item.PSIsContainer) {
            Write-Host "$prefix $($item.Name)`n"
            Get-DirTree $item.FullName ($indent + 1)
        } else {
            $owner = (Get-Acl $item.FullName).Owner
            Write-Host "$prefix $($item.Name) - $owner`n"
        }
    }
}
Get-DirTree $rootPath

Linux / macOS 环境

使用系统自带命令即可实现:

  • 基础版本,输出全路径+所有者:
find 替换为你要扫描的根目录路径 -exec ls -ld {} \; | awk '{print $9, " - ", $3}'
  • 树形缩进版本,先安装tree工具(Ubuntu/Debian下执行apt install tree,macOS下执行brew install tree),之后运行:
tree -u 替换为你要扫描的根目录路径

-u参数会默认在每个条目后追加所有者信息,自带层级缩进效果。

跨平台通用方案(Python)

如果需要在多个操作系统使用,可以运行以下Python脚本,类Unix系统可直接运行,Windows系统需要先安装pywin32依赖用于获取文件所有者:

import os
from pathlib import Path
# Windows系统打开下面两行注释,删除类Unix的所有者获取逻辑
# import win32api
# import win32security

def print_dir_tree(path, indent=0):
    for item in Path(path).iterdir():
        prefix = ">" + "    " * indent
        if item.is_dir():
            print(f"{prefix} {item.name}")
            print_dir_tree(item, indent + 1)
        else:
            # 类Unix系统所有者获取逻辑
            import pwd
            owner = pwd.getpwuid(os.stat(item).st_uid).pw_name
            # Windows系统所有者获取逻辑
            # sd = win32security.GetFileSecurity(str(item), win32security.OWNER_SECURITY_INFORMATION)
            # owner_sid = sd.GetSecurityDescriptorOwner()
            # name, domain, _ = win32security.LookupAccountSid(None, owner_sid)
            # owner = f"{domain}\\{name}"
            print(f"{prefix} {item.name} - {owner}")

if __name__ == "__main__":
    root_path = "替换为你要扫描的根目录路径"
    print_dir_tree(root_path)

内容的提问来源于stack exchange,提问作者MConvery

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 01:15:04