Get DirectoryName for folder

Marcus Östman 21 Reputation points

I have this script which exports a list of files and folders to a csv.

Get-ChildItem -path D:\VmWare -Recurse | Select-Object DirectoryName, Name, Extension, Length | Export-Csv -Path D:\Temp\Test.csv -Encoding Unicode -NoTypeInformation

I trying to figure out if it's possible to get DirectoryName for a folder. If I choose 'Fullname' I also get file name on files, which I don't want to.
I found this line, but I don't see how to incorporate it to the script above.

foreach {Split-Path -Path $_.Fullname -Parent | Split-Path -NoQualifier }


Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
4,745 questions
No comments
{count} votes

3 answers

Sort by: Newest
  1. Keith Miller 1 Reputation point

    Make DirectoryName a calculated property:

    Get-ChildItem -path D:\VmWare -Recurse |
        Select @{ N = 'DirectoryName' ; E = {
            If ( ! ( $_.PSIsContainer ))
                { $_.DirectoryName }
                { Split-Path $_.FullName }
        }}, Name, Extension, Length |
    Export-Csv -Path D:\Temp\Test.csv -Encoding Unicode -NoTypeInformation
  2. Ian Xue (Shanghai Wicresoft Co., Ltd.) 18,771 Reputation points Microsoft Vendor


    According to your screenshot, are you trying to get the full path of the parent directory of a directory? If yes you may try this

    Get-ChildItem -path D:\VmWare -Recurse -Directory | ForEach-Object { Split-Path -Path $_.FullName -Parent }  

    Best Regards,


    If the Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

  3. Rich Matheisen 36,241 Reputation points

    Do you want only directories in the list? If so, add the "-Directory" switch to the Get-ChildItem cmdlet.

    If you want directories and files in the list, then this should help:

    Get-ChildItem c:\junk -Recurse | 
        ForEach-Object {
            if ($_.PSIsContainer){