PowerShell - Why is an array used in this line of code, please?

Viewed 44

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!

2 Answers

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.

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

Related