PowerShell Get-ChildItem

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

July 1st, 2013 5:44pm

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)"
}

Free Windows Admin Tool Kit Click here and download it now
July 1st, 2013 10:58pm

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,

July 2nd, 2013 2:26am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics