Select-String need CreationTime along with Filename, Line, LineNumber

31 Views Asked by At

I'm trying to find files in a directory which contain a string. I'm okay with that part, but I can't figure out how to get the CreationTime for the file containing the string.

This gives me what I need except for CreationTime.

Get-ChildItem | 
    Select-String -Pattern 'GREEN' | 
    select-object -Property Filename, Line, LineNumber

Trying foreach but can't get at the file CreationTime.


    $collection = Get-ChildItem

    foreach ($currentItemName in $collection) {
        if ( $currentItemName | Select-String -Pattern 'GREEN') {
         
          $currentItemName |Select-String -Pattern 'GREEN' | `your text`
          Select-Object -Property Filename, Line, LineNumber;
        
          $currentItemName | Select-Object -Property CreationTime;
       
        } 
    }

My lack of understanding regarding object type is part of my problem. The objects in Get-ChildItem includes time details, but the object type after Select-String does not.

1

There are 1 best solutions below

0
Mathias R. Jessen On

You can use Select-Object to construct new properties on-the-fly by using a so-called calculated property expression:

Get-ChildItem | 
    Select-String -Pattern 'GREEN' | 
    Select-Object -Property Filename, Line, LineNumber, @{Name='CreationTime';Expression={
        Get-ItemPropertyValue -LiteralPath $_.Path -Name CreationTime
    }}

Alternatively use nested loops to keep track of the file object piped to Select-String and then construct your own custom output objects by combining it with the selection results:

foreach($file in Get-ChildItem) {
  foreach($matchingLine in $file |Select-String GREEN) {
    [pscustomobject]@{
      Filename     = $matchingLine.Filename
      Line         = $matchingLine.Line
      LineNumber   = $matchingLine.LineNumber
      CreationTime = $file.CreationTime
    }
  }
}