Powershell-列出所有文件夹,子文件夹和每个包含的文件递归,但以格式化的方式树视图列出

问题描述

我在powershell上使用以下命令来创建特定目录中所有文件和子文件夹的列表:

get-childitem -path c:\users\username\desktop\test -recurse | select name

因此,假设我的桌面上有一个名为“ test”的文件夹,并且在此文件夹中,我有三个文件一个文件夹,它本身还包含其他文件和子文件夹,依此类推,我确实得到了类似的输出: / p>

subfolder 1 of "test"
file 1 in "test"
file 2 in "test"
file 3 in "test"
subfolder a of "subfolder 1"
file 1 in subfolder 1
file 2 in subfolder 1
file 3 in subfolder 1
file 1 in subfolder a
file 2 in subfolder a
file 3 in subfolder a

这很好,但是我想获得另一种输出,如下所示:

+  c:\users\username\desktop\test
|  -  file 1 in "test"
|  -  file 2 in "test"
|  -  file 3 in "test"
|--+  subfolder 1 of "test"
|  |  -  file 1 in subfolder 1
|  |  -  file 2 in subfolder 1
|  |  -  file 3 in subfolder 1
|  |--+  subfolder a of "subfolder 1"
|  |  |  -  file 1 in subfolder a
|  |  |  -  file 2 in subfolder a
|  |  |  -  file 3 in subfolder a
|--+  subfolder 2 of "test"
|  |  -
|  |  .
|  .  .
.  .
.

是否有可能(如果是,怎么办?)获得像这样的输出? 我知道当时有一个dos命令称为“ tree”,但由于其局限性,它无法与powershell中的get-childitem输出配合使用。 Powershell中是否存在某种等效命令,或者我可以使用get-childitem命令及其开关/添加项/ ...来做到这一点吗?

抱歉,我的英语不好。 而且:对不起,我是Powershell的初学者。

谢谢您的帮助。

解决方法

您习惯于从cmd中使用的旧“树”是system32文件夹中的应用程序,而不是某些硬编码的cmd功能。

因此您仍然可以像往常一样从powershell运行它。

例如

Tree 'C:\Foldername'

Robocopy和其他一些知名应用程序的工作方式相同。

可以在$ LastExitCode中捕获外部程序中的错误,而不是通常的$ Error。这些代码的含义将取决于程序。

,

您可以从Powershell调用任何cmd / DOS可执行文件。只要您这样做正确。在consolehost(powershell.exe / pwsh.exe)中,它实际上与使用cmd.exe相同,但是在ISE中则有所不同。您不能在ISE中使用交互式命令。您可以使用该命令,但必须通过它。

在PowerShell控制台主机(powershell.exe / pwsh.exe)中,只需键入...

$PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.19041.1
PSEdition                      Desktop
PSCompatibleVersions           {1.0,2.0,3.0,4.0,5.0,5.1.19041.1}
BuildVersion                   10.0.19041.1
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1


tree |more
Folder PATH listing for volume Data
Volume serial number is CE3D-F392
D:.
├───.vs
│   └───Scripts
│       └───v16
├───.vscode
...

PowerShell: Running Executables

没有理由从头开始。有很多示例甚至模块提供了此功能。

快速搜索将显示您从调整开始或按原样使用...

'PowerShell treeView':

PowerTip: View Directory List as Tree by Using PowerShell 使用PowerShell社区扩展项目中的Show-Tree cmdlet:

Find-Module -Name pscx | 
Format-Table -AutoSize
# Results
<#
Version Name Repository Description                                                                                          
------- ---- ---------- -----------                                                                                          
3.3.2   Pscx PSGallery  PowerShell Community Extensions (PSCX) base module which implements a general-purpose set of Cmdlets.
#>

Show-Tree e:\data –depth 2

https://serverfault.com/questions/744660/powershell-populating-treeview-with-directory-hierarchy

$objDriveLetters = GET-WMIOBJECT –query "SELECT * from win32_logicaldisk"
$form = New-Object System.Windows.Forms.Form
$treeView = New-Object System.Windows.Forms.TreeView
$treeView.Dock = 'Fill'
$treeView.CheckBoxes = $true

foreach ($iDrive in $objDriveLetters)
    {
        $DriveRoot = Get-Item $iDrive.DeviceID
        #$FolderRoot = Get-ChildItem -Path $iDrive.DeviceID
        $FolderRoot = Get-Item -Path $iDrive.DeviceID
        $treeView.Nodes.Add($FolderRoot.FullName,$FolderRoot.FullName)
    }

$form.Controls.Add($treeView)
$form.ShowDialog()

使用PowerShell创建文件系统大小树视图:

https://key2consulting.com/powershell-file-directory-tree-view

    #Variables that need to be set for each run
    $startFolder = "C:\Program Files"; #The starting folder to analyze
    $sourceHTMLFile = "C:\finalTemplate.html"; #The html source template file
    $destinationHTMLFile = "C:\final.html"; #The final html file that will be produced,#does not need to exist

    $htmlLines = @();

    #Function that creates a folder detail record
    function CreateFolderDetailRecord
    {
        param([string]$FolderPath)
    
        #Get the total size of the folder by recursively summing its children
        $subFolderItems = Get-ChildItem $FolderPath -recurse -force | Where-Object {$_.PSIsContainer -eq $false} | Measure-Object -property Length -sum | Select-Object Sum
        $folderSizeRaw = 0;
        $folderSize = 0;
        $units = "";

        #Account for no children
        if($subFolderItems.sum -gt 0)
        {
            $folderSizeRaw = $subFolderItems.sum;     
        }    

        #Determine units for a more friendly output
        if(($subFolderItems.sum / 1GB) -ge 1)
        {
            $units = "GB"
            $folderSize = [math]::Round(($subFolderItems.sum / 1GB),2)
        }
        else
        {
            if(($subFolderItems.sum / 1MB) -ge 1)
            {
                $units = "MB"
                $folderSize = [math]::Round(($subFolderItems.sum / 1MB),2)
            }
            else
            {
                $units = "KB"
                $folderSize = [math]::Round(($subFolderItems.sum / 1KB),2)
            }
        }

        #Create an object with the given properties
        $newFolderRecord = New-Object –TypeName PSObject
        $newFolderRecord | Add-Member –MemberType NoteProperty –Name FolderPath –Value $FolderPath;
        $newFolderRecord | Add-Member –MemberType NoteProperty –Name FolderSizeRaw –Value $folderSizeRaw
        $newFolderRecord | Add-Member –MemberType NoteProperty –Name FolderSizeInUnits –Value $folderSize;
        $newFolderRecord | Add-Member –MemberType NoteProperty –Name Units –Value $units;

        return $newFolderRecord;
    }

    #Function that recursively creates the html for the output,given a starting location
    function GetAllFolderDetails
    {
        param([string]$FolderPath)    

        $recursiveHTML = @();

        #Get properties used for processing
        $folderItem = Get-Item -Path $FolderPath
        $folderDetails = CreateFolderDetailRecord -FolderPath $FolderPath
        $subFolders = Get-ChildItem $FolderPath | Where-Object {$_.PSIsContainer -eq $true} | Sort-Object

        #If has subfolders,create hmtl drilldown. 
        if($subFolders.Count -gt 0)
        {
            $recursiveHTML += "<li><span class='caret'>" + $folderItem.Name + " (<span style='color:red'>" + $folderDetails.FolderSizeInUnits + " " + $folderDetails.Units + "</span>)" + "</span>"
            $recursiveHTML += "<ul class='nested'>"
        }
        else
        {
            $recursiveHTML += "<li>" + $folderItem.Name + " (<span style='color:red'>" + $folderDetails.FolderSizeInUnits + " " + $folderDetails.Units + "</span>)";
        }

        #Recursively call this function for all subfolders
        foreach($subFolder in $subFolders)
        {
            $recursiveHTML += GetAllFolderDetails -FolderPath $subFolder.FullName;
        }

        #Close up all tags
        if($subFolders.Count -gt 0)
        {
            $recursiveHTML += "</ul>";
        }

        $recursiveHTML += "</li>";
    
        return $recursiveHTML
    }

    #Processing Starts Here

    #Opening html
    $htmlLines += "<ul id='myUL'>"

    #This function call will return all of the recursive html for the startign folder and below
    $htmlLines += GetAllFolderDetails -FolderPath $startFolder

    #Closing html
    $htmlLines += "</ul>"

    #Get the html template,replace the template with generated code and write to the final html file
    $sourceHTML = Get-Content -Path $sourceHTMLFile;
    $destinationHTML = $sourceHTML.Replace("[FinalHTML]",$htmlLines);
    $destinationHTML | Set-Content $destinationHTMLFile 

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...