Search code examples
arrayspowershellobjectget-childitem

How to extract properties from a powershell object


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  = @()

Solution

  • 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