0

How can an array of files, as found through tree, be populated?

posh> 
posh>  tree ./  | Get-Item

    Directory: /home/nicholas/powershell

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d----           2/21/2021  5:42 PM                regex
Get-Item: Cannot find path '/home/nicholas/powershell/regex/├── a.log' because it does not exist.
..
Get-Item: Cannot bind argument to parameter 'Path' because it is an empty string.
Get-Item: Cannot find path '/home/nicholas/powershell/regex/0 directories, 16 files' because it does not exist.

posh> 

This example has no sub-directories, but for more complex directories, with sub-directories, looking to capture, for each file, its full path and filename.

Specifically, to then search the files -- but the question is of a somewhat general nature.

see also:

Use PowerShell to generate a list of files and directories

https://superuser.com/q/1270040/977796

1 Answers1

2

tree is a CLI program found on windows and most Unix-style OSes for drawing a visual representation of a file structure. It does not generate an array of directories.

In powershell if you want to get the items of a directory structure recursively and save them to a variable (which would be an array except in the case where only a single item is returned) use the following:

$tree = Get-ChildItem -Recurse

This will store the result in the variable $tree. You can use the -path parameter if you want to start not at the current location. E.g.

$tree = Get-ChildItem -Path "/home/dave" -Recurse
Mark Winckle
  • 111
  • 5
  • Nice, but can you elaborate on what Unix-like platforms come with a `tree` utility? Neither macOS 11 nor Ubuntu 18.04 come with one, for instance. Since the default behavior of `tree.com` on Windows is just to print _directories_, the analogous `Get-ChildItem` call requires the `-Directory` switch. – mklement0 Feb 22 '21 at 03:04
  • 1
    To my recollection I had to install tree @mklement0 (for ubuntu) – Nicholas Saunders Feb 22 '21 at 05:15