none
PowerShell Get-ChildItem

    Question

  • I want to get the directorys and file names of a path in a nice object. My problem is creating the one object out of the two different objects that are returned from get-childitem. I would like a dir name associated with each file object so later I can spin thru this object as needed.

    Thank you,

    Bob

    Monday, July 01, 2013 9:41 PM

Answers

  • I'm not sure what you're trying to accomplish.  Get-ChildItem (and any other PowerShell cmdlet that can return multiple results) already gives you an Array object which contains the results.  You can assign the results of Get-ChildItem to a variable, then access its contents later.  Something like this:

    $results = Get-ChildItem -Path "C:\windows\system32\*.vbs" -Recurse
    
    foreach ($object in $results) {
        Write-Host "Child item name: $($object.Name)"
    
        # Files have a DirectoryName property, but Directories
        # do not.  Parent.FullName will work for both.
        Write-Host "Parent directory: $($object.Parent.FullName)"
    }
    

    Tuesday, July 02, 2013 2:55 AM
  • Normally, Get-ChildItem cmdlet return IO.FileInfo and IO.DirectoryInfo array objects. If you want to get custom object as result, pls try with following;

    dir C:\Temp -Recurse | %{ if ($_.PsIsContainer) { New-Object PsObject -Property @{Directory=$_.fullName; FileName=''}} else { New-Object PsObject -Property @{Directory=$_.Directory; FileName=$_.Name}} } | sort directory
    You can also use export-csv cmdlet to save the result as csv file.

    rgds,

    Tuesday, July 02, 2013 6:23 AM

All replies

  • I'm not sure what you're trying to accomplish.  Get-ChildItem (and any other PowerShell cmdlet that can return multiple results) already gives you an Array object which contains the results.  You can assign the results of Get-ChildItem to a variable, then access its contents later.  Something like this:

    $results = Get-ChildItem -Path "C:\windows\system32\*.vbs" -Recurse
    
    foreach ($object in $results) {
        Write-Host "Child item name: $($object.Name)"
    
        # Files have a DirectoryName property, but Directories
        # do not.  Parent.FullName will work for both.
        Write-Host "Parent directory: $($object.Parent.FullName)"
    }
    

    Tuesday, July 02, 2013 2:55 AM
  • Normally, Get-ChildItem cmdlet return IO.FileInfo and IO.DirectoryInfo array objects. If you want to get custom object as result, pls try with following;

    dir C:\Temp -Recurse | %{ if ($_.PsIsContainer) { New-Object PsObject -Property @{Directory=$_.fullName; FileName=''}} else { New-Object PsObject -Property @{Directory=$_.Directory; FileName=$_.Name}} } | sort directory
    You can also use export-csv cmdlet to save the result as csv file.

    rgds,

    Tuesday, July 02, 2013 6:23 AM