0

I am trying to extract properties of object from the results obtained from Get-ChildItem in Powershell as it may be seen below

$folderPath = "C:\Users\me\someThing1\someThing2"
$fileNames = Get-ChildItem  -Path $folderPath -Filter *.pdf -recurse | ForEach-Object { 
    $_.FullName  
    $_.LastWriteTime
    $_.Exists
    $_.BaseName
    $_.Extension
}
# Extracting properties
foreach ($file in $fileNames) {
    Write-Host $file
  
}

When I use the Write-Host command, I get property values of FullName, LastWriteTime, Exists, BaseName, Extension printed to the terminal for each file. But I am unable to get individual property value.

For e.g., I tried

Write-Host $file."BaseName"

It does not work. Can someone help me extract individual property from each file? The purpose is to store each property of each file into an array as given below

$FullNames = @()
$LastWriteTimes  = @()
$Exists = @()
$BaseNames  = @()
$Extensions  = @()
rhythmo
  • 859
  • 2
  • 9
  • 21
  • 2
    Remove ForEach-Object completely – Mathias R. Jessen Mar 19 '21 at 23:01
  • 2
    Yup. You also don't need to save each property on each of those arrays. i.e: after you do `$fileNames = Get-ChildItem -Path $folderPath -Filter *.pdf -recurse` the "FullName" of all your files will be here `$fileNames.FullName`, the "lastWriteTime" will be here `$fileNames.lastWriteTime` and so on. – Santiago Squarzon Mar 19 '21 at 23:11
  • 1
    These 2 are correct. Also, even tho it's not needed in this case, you should try swapping to an `[System.Collections.ArrayList]` instead of a fixed array when saving output. – Abraham Zinala Mar 19 '21 at 23:13
  • In addition, `Write-Host` is almost always not good to use. If you want to cast a property to your PS Host you can just do `$file.BaseName` inside your `foreach` loop or if you need a string you can do `"Base Name: {0}" -f $file.BaseName` or `"Base Name: $($file.BaseName)"` – Santiago Squarzon Mar 19 '21 at 23:16
  • Thank you All. You have been super helpful! – rhythmo Mar 19 '21 at 23:41
  • Does this answer your question? [How Does Member Enumeration Work in PowerShell 3?](https://stackoverflow.com/questions/12131416/how-does-member-enumeration-work-in-powershell-3) – zett42 Mar 20 '21 at 10:32

1 Answers1

3

Just posting the revised code that extracts properties into individual arrays just so that someone else might find it helpful. Thanks to all who supported.

# Edit the Folder Path as desired
$folderPath = "C:\Users\me\someThing1\someThing2"

# Getting File Objects
$files = Get-ChildItem  -Path $folderPath -recurse 
   

# Extracting properties into individual Arrays
$FullNames = $files.FullName
$LastWriteTimes = $files.LastWriteTime
$file_Exists = $files.Exists
$BaseNames = $files.BaseName
$Extensions = $files.Extension
rhythmo
  • 859
  • 2
  • 9
  • 21