【问题标题】:PowerShell - Listing all Folders, Subfolders and each contained files (recursive) but in a formatted way (Tree-View)PowerShell - 列出所有文件夹、子文件夹和每个包含的文件(递归)但以格式化方式(树视图)
【发布时间】:2020-10-07 18:16:15
【问题描述】:

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

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

所以假设我的桌面上有一个名为“test”的文件夹,在这个文件夹中我有三个文件和一个子文件夹,它本身包含更多的文件和子文件夹等等,我确实得到了这样的输出:

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"
|  |  -
|  |  .
|  .  .
.  .
.

是否有可能(如果是 - 那么如何?)得到这样的输出?

我知道当时有一个名为“tree”的 dos 命令,但由于其局限性,它不能与 PowerShell 中的 get-childitem 的输出一起使用。 PowerShell 中是否有某种等效命令,或者我可以使用 get-childitem 命令及其开关/添加/...来执行此操作吗?

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

【问题讨论】:

    标签: powershell sorting directory get-childitem


    【解决方案1】:

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

    所以你仍然可以像往常一样从 powershell 运行它。

    例如

    Tree 'C:\Foldername'
    

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

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

    【讨论】:

      【解决方案2】:

      您可以从 Powershell 调用任何 cmd/DOS 可执行文件。只要你做得正确。在控制台主机 (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 
      

      【讨论】:

        猜你喜欢
        • 2013-05-01
        • 1970-01-01
        • 2019-06-26
        • 1970-01-01
        • 2021-10-19
        • 2012-02-22
        • 1970-01-01
        • 1970-01-01
        • 2018-08-06
        相关资源
        最近更新 更多