Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

powershell get-childitem to csv with details

I am trying to create a CSV file for a file share that has deep folder structure.

I want the CSV to look like:

filename, filepath, file type, folderStructure

So far I have the following:

#Get-ChildItem -Path D:\ -Recurse
$directory="d:\"
gci $directory -recurse |
where {$_.psiscontainer} |
foreach {
    get-childitem $_.fullname |
    sort creationtime |
    select -expand fullname -last 1
}
like image 436
torres Avatar asked Sep 13 '25 06:09

torres


1 Answers

You don't need to recurse a recursive in Powershell. It will automatically go through all of the subdirectories of subdirectories.

I am also a little unsure of some of the information you wanted, but here is a script that does what you want mostly I believe and is IMO a little better to read.

Get-ChildItem -Path X:\Test -Recurse |`
foreach{
$Item = $_
$Type = $_.Extension
$Path = $_.FullName
$Folder = $_.PSIsContainer
$Age = $_.CreationTime

$Path | Select-Object `
    @{n="Name";e={$Item}},`
    @{n="Created";e={$Age}},`
    @{n="filePath";e={$Path}},`
    @{n="Extension";e={if($Folder){"Folder"}else{$Type}}}`
}| Export-Csv X:\Test\Results.csv -NoTypeInformation 

You will need to change your path, as I created this for a test. My results look like this in Excel:

+-------------------------------+----------------+-------------------------------------+-----------+
|             Name              |    Created     |              filePath               | Extension |
+-------------------------------+----------------+-------------------------------------+-----------+
|         test2                 | 3/6/2013 19:21 | X:\Test\test2                       | Folder    |
|         Results.csv           | 3/6/2013 19:51 | X:\Test\Results.csv                 | .csv      |
|         test3                 | 3/6/2013 19:21 | X:\Test\test2\test3                 | Folder    |
|         New Text Document.txt | 3/6/2013 19:21 | X:\Test\test2\New Text Document.txt | .txt      |
+-------------------------------+----------------+-------------------------------------+-----------+

Where it says "Folder" for the Extension just it returning that it is a directory instead of a blank (No extension).

like image 53
Austin T French Avatar answered Sep 15 '25 21:09

Austin T French