Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

powershell - List main directory and its sub-directories using directory name property in power shell

I have the following tree structure of a folder called test.

enter image description here

What I am trying to achieve is to list the main directory and its sub-directories under the column directory name using the Get-ChildItem property(Code is shown below).

Here's the code that I wrote in powershell :

Get-ChildItem -Path C:UsersUSERDesktopest -Recurse | Select-Object directoryname, Name, LastWriteTime, CreationTime | Export-Csv -Path 'C:UsersUSERDesktopfiletxt.csv' -Encoding ascii -NoTypeInformation

What I achieved is the following : enter image description here

As you can see, the directory name for Folder1 and Folder2 is missing and it should've been taken the same name of the path. Similarly for SubFolder1, the directory name should be Main PathFolder1 and etc... My expected result is the following : enter image description here

Can someone please help me find a solution for the following problem ? Thank you

question from:https://stackoverflow.com/questions/65947709/list-main-directory-and-its-sub-directories-using-directory-name-property-in-pow

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Folders do not have a property "directoryname". You can use a calculated property with a Split-Path to extract the information you're after.

Get-ChildItem -Path D:sampleest-files -Recurse |
    Select-Object -Property @{Name='Path';Expression={Split-Path -Path $_.FullName -Parent}},Name, LastWriteTime, CreationTime, @{Name='Extension';Expression={if (-not $_.PSIsContainer) {$_.Extension}}} 

And BTW: Folders actually do not have a "LastWriteTime". They show the "LastWriteTime" from the newest file they contain. ;-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...