使用PowerShell生成文件和目录列表

Yet*_*ser 21 powershell powershell-2.0 get-childitem

我正在编写一个PowerShell脚本来制作几个目录并将一堆文件复制到一起来"编译"一些技术文档.我想生成一个文件和目录的清单作为自述文件的一部分,我希望PowerShell这样做,因为我已经在PowerShell中进行"编译"了.

我已经做了一些搜索,似乎我需要使用cmdlet"Get-ChildItem",但是它给了我太多的数据,而且我不清楚如何格式化和修剪我不知道的内容想得到我想要的结果.

我想要一个类似于此的输出:

Directory
     file
     file
     file
Directory
     file
     file
     file
     Subdirectory
          file
          file
          file
Run Code Online (Sandbox Code Playgroud)

或者类似这样的事情:

+---FinGen
|   \---doc
+---testVBFilter
|   \---html
\---winzip
Run Code Online (Sandbox Code Playgroud)

换句话说,树结构的某种基本的可视化ASCII表示与目录和文件名并没有别的.我见过程序执行此操作,但我不确定PowerShell是否可以执行此操作.

PowerShell可以这样做吗?如果是这样,Get-ChildItem会是正确的cmdlet吗?

Mat*_*att 40

在你的特殊情况下你想要的是什么Tree /f.你有一个评论,询问如何去除前面的部分,谈论音量,序列号和驱动器号.这可以在将输出发送到文件之前过滤输出.

$Path = "C:\temp"
Tree $Path /F | Select-Object -Skip 2 | Set-Content C:\temp\output.tkt
Run Code Online (Sandbox Code Playgroud)

上面示例中的树输出是System.Array我们可以操作的.Select-Object -Skip 2将删除包含该数据的前两行.此外,如果Keith Hill在附近,他还会推荐包含cmdlet的PowerShell社区扩展(PSCX)Show-Tree.如果你好奇,请从这里下载.那里有很多强大的东西.

  • NP。我确实会犯错。 (2认同)

Rom*_*man 7

在 中Windows,导航至感兴趣的目录

Shift+ 右键单击​​鼠标 ->Open PowerShell window here

Get-ChildItem | tree /f > tree.log
Run Code Online (Sandbox Code Playgroud)


小智 5

以下脚本会将树显示为窗口,可以将其添加到脚本中存在的任何表单中

function tree {

   [void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
   [void][System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")

   # create Window
   $Form = New-Object System.Windows.Forms.Form
   $Form.Text = "Files"
   $Form.Size = New-Object System.Drawing.Size(390, 390)
   # create Treeview-Object
   $TreeView = New-Object System.Windows.Forms.TreeView
   $TreeView.Location = New-Object System.Drawing.Point(48, 12)
   $TreeView.Size = New-Object System.Drawing.Size(290, 322)
   $Form.Controls.Add($TreeView)

   ###### Add Nodes to Treeview
   $rootnode = New-Object System.Windows.Forms.TreeNode
   $rootnode.text = "Root"
   $rootnode.name = "Root"
   [void]$TreeView.Nodes.Add($rootnode)

   #here i'm going to import the csv file into an array
   $array=@(Get-ChildItem -Path D:\personalWorkspace\node)
   Write-Host $array
   foreach ( $obj in $array ) {                                                                                                             
        Write-Host $obj
        $subnode = New-Object System.Windows.Forms.TreeNode
        $subnode.text = $obj
        [void]$rootnode.Nodes.Add($subnode)
     }

   # Show Form // this always needs to be at the bottom of the script!
   $Form.Add_Shown({$Form.Activate()})
   [void] $Form.ShowDialog()

   }
   tree
Run Code Online (Sandbox Code Playgroud)