Powershell-查詢當前文件目錄層級結構

日常工作中我們往往有需要導出當前共享環境或磁盤文件目錄層級結構等的需求,最早在目錄少的情況下我們使用CMD下tree 命令可以很清晰的看到目錄、文件層級結構,那麼我們又如何通過powershell直觀顯示或導出某文件目錄或盤符目錄層級結構呢?

DOS下查看目錄、文件結構:

tree /?
以圖形顯示驅動器或路徑的文件夾結構。
TREE [drive:][path] [/F] [/A]
/F   顯示每個文件夾中文件的名稱。
/A   使用 ASCII 字符,而不使用擴展字符。

image


Powershell查看目錄、文件結構:

其實我們通過powershell命令也可以搭配tree命令使用,簡單操作如下:

Get-ChildItem D:\SW_Office_Plus |tree /f
Get-ChildItem D:\SW_Office_Plus |tree /A

Get-ChildItem :獲取一個或多個指定位置中的項和子項。

獲取當前目錄下文件夾名稱:

Get-ChildItem D:\SW_Office_Plus | ?{$_.psiscontainer -eq $true}

獲取當前目錄下文件名稱:
Get-ChildItem D:\SW_Office_Plus | ?{$_.psiscontainer -eq $false}

image

接下來進入我們今天的主題內容,如何查看當前目錄下文件層級,具體命令如下:

Get-ChildItem -Recurse -Directory -Depth 3 |select FullName

Get-ChildItem D:\SW_Office_Plus  -Recurse -Directory -Depth 3 |select Fullname

image

如果需要對結果進行導出,可通過如下命令操作:

Get-ChildItem -Recurse -Directory -Depth 3 |select FullName | Export-Csv d:\fullname.csv -Encoding UTF8 –NoTypeInformation


PS.補充:導出文件、文件目錄名稱、創建時間、格式等等信息:

Get-ChildItem -Path D:\SW_Office_Plus -Recurse |`
foreach{
$Item = $_
$Type = $_.Extension
$Path = $_.FullName
$ParentS = ($_.Fullname).split("\")
$Parent = $ParentS[@($ParentS.Length - 2)]
$ParentPath = $_.PSParentPath
$ParentPathSplit = ($_.PSParentPath).split("::")
$ParentPathFinal = $ParentPathSplit[@($ParentPathSplit.Length -1)]
#$ParentPath = [io.path]::GetDirectoryName($myDirectory)
$Folder = $_.PSIsContainer
$Age = $_.CreationTime
$Path | Select-Object `
    @{n="Name";e={$Item}},`
    @{n="Created";e={$Age}},`
    @{n="Folder Name";e={if($Parent){$Parent}else{$Parent}}},`
    @{n="filePath";e={$Path}},`
    @{n="Extension";e={if($Folder){"Folder"}else{$Type}}},`
    @{n="Folder Name 2";e={if($Parent){$Parent}else{$Parent}}},`
    #@{n="Folder Path";e={$ParentPath}},`
    @{n="Folder Path 2";e={$ParentPathFinal}}`
}| Export-Csv d:\Folder.csv -Encoding UTF8 -NoTypeInformation

image

導出後格式如下,可自行篩選,該腳本內容具體可參考該link

image

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章