2

I have the following code that looks for a string in multiple files, part of which I found here.

$path = C:\Windows
Set-Location -path $path

$searchWords = 'log.txt'

Foreach ($sw in $searchWords)
{
    Get-Childitem -Path $path -Recurse -include "*.txt","*.dll" | 
    Select-String -Pattern "$sw" | 
    Select Path,LineNumber,@{n='SearchWord';e={$sw}}
}

The syntax I don't think I understand is this part in the last line:

@{n='SearchWord';e={$sw}}

I'll explain what I think I understand and then ask questions.

  1. @ I think means it is an array
  2. n= is shorthand for 'name'
  3. the colon(;) is separating the name of the column and the expression that fills the column.
  4. e= is shorthand for expression
  5. {$sw} - the brackets are necessary here to encapsulate the expression.

Question(s):

  1. Why is an array used to populate this column?
  2. Why must an expression be used and not just the variable '$sw'?

Thanks for the help!

JM1
  • 1,595
  • 5
  • 19
  • 41
  • 2
    You are looking at [Calculated Properties](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/select-object?view=powershell-7.1#example-10--create-calculated-properties-for-each-inputobject). – AdminOfThings Jan 11 '21 at 14:32

2 Answers2

6

It's not an array but hash table. In the quoted code, a calculated property is used. Usually calculated properties are used to, well, calculate stuff. For example, free disk space can be calculated as percents as per this answer:

@{Name = 'Free';Expression = { "{0:N0}%" -f (($_.FreeSpace/$_.Size) * 100) } }

In the sample you used, calculated property is used to add a label property that contains the search term used on each iteration of the foreach loop.

vonPryz
  • 22,996
  • 7
  • 54
  • 65
1

Thanks to everyone. I didn't know what a calculated property was. @vonPryz helped me understand this. For others trying to understand calculated properties, here are some links which further explain Calculated Properties.

Adam Bertram: Using PowerShell's Calculated Properties

Microsoft Documentation: Calculated Properties

JM1
  • 1,595
  • 5
  • 19
  • 41