Carlos
Carlos

Reputation: 257

Using Get-ChildItem to retrieve folder,name,fullname

I'm currently using this script to pull the Name,Folder,Foldername from a given path:

   Get-ChildItem "C:\user\desktop"  | Select Name, `
  @{ n = 'Folder'; e = { Convert-Path $_.PSParentPath } }, `
  @{ n = 'Foldername'; e = { ($_.PSPath -split '[\\]')[-2] } } ,
  @{ n = 'Fullname'; e = { Convert-Path $_.PSParentPath } } |
    Export-Csv "C:\user\desktop\txt.txt" -Encoding Utf8 -NoTypeInformation

I am having trouble getting @{ n = 'Fullname'; e = { Convert-Path $_.PSParentPath } } to pull through the full file path.

Any help greatly appreciated.

Upvotes: 10

Views: 104120

Answers (2)

mklement0
mklement0

Reputation: 437933

You mistakenly referenced PSParentPath when you meant PSPath to get the full name (full filesystem path):

Get-ChildItem "C:\user\desktop" | Select Name, `
  @{ n = 'Folder'; e = { Convert-Path $_.PSParentPath } }, `
  @{ n = 'Foldername'; e = { ($_.PSPath -split '[\\]')[-2] } } ,
  @{ n = 'Fullname'; e = { Convert-Path $_.PSPath } }  # NOT $_.PS*Parent*Path

However, as others have pointed out, the full path is a standard property on the output objects produced by Get-ChildItem (instances of type [System.IO.DirectoryInfo]), so you can simply reference the FullName property:

Get-ChildItem "C:\user\desktop" | Select Name, `
  @{ n = 'Folder'; e = { Convert-Path $_.PSParentPath } }, `
  @{ n = 'Foldername'; e = { ($_.PSPath -split '[\\]')[-2] } } ,
  FullName

P.S.: '\\' will do as the RHS of the -split operator, but if you wanted to be cross-platform-friendly, you could use [\\/]

Note: The hashtable-based technique used above (@{ n = ...; e = ... }, where n is short for Name and e for Expression) is called a calculated property, described in the conceptual about_Calculated_Properties help topic, across all cmdlets that support calculated properties.

Upvotes: 11

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

DirectoryInfo objects (the output of Get-ChildItem for folders) have properties Name and FullName with the name and full path of the folder. They also have a property Parent that returns another DirectoryInfo object for the parent folder. You can add that information as a calculated property.

Since you basically want to add the grandparent name and path for the listed items, and that information doesn't change because you don't recurse, you can determine them once and add them as static information:

$dir = 'C:\some\folder'

$folder     = (Get-Item $dir).Parent
$folderName = $folder.Name
$folderPath = $folder.FullName

Get-ChildItem $dir |
    Select-Object Name, FullName,
        @{n='FolderName';e={$folderName}},
        @{n='Folder';e={$folderPath}} |
    Export-Csv 'C:\path\to\output.csv' -Encoding UTF8 -NoType

Upvotes: 6

Related Questions