Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
164 views
in Technique[技术] by (71.8m points)

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

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...