2

I want to search for all files, of .exe.config for certain strings. I want to list the files with those strings and then list all of the files that were checked. I can get it to find the files with the strings with:

Get-ChildItem -Path c:\ -I *.exe.config -R| Select-String 'string1','string2'

My issue, I can't figure out how to get it to show all the .exe.config files that it checked (without searching the computer again). I thought I could save the intial search results into a variable. Then run through that with a for loop, but I can't even get the right info into a variable. I tried several variations of below, but $files is always empty. Also, I'm not sold on this approach, so if anyone has a completely different method, that would be fine

$files = (Get-ChildItem -Path c:\ -I *.exe.config -R).Path
$files = (Get-ChildItem -Path c:\ -I *.exe.config -R | select fullname)

1 Answer 1

2

Use the common -OutVariable parameter to capture Get-ChildItem's output in a variable of your choice, separately from what the pipeline overall outputs:

Get-ChildItem c:\ -Include *.exe.config -Recurse -OutVariable files |
  Select-String 'string1','string2'

Variable $file now contains all System.IO.FileInfo instances output by Get-ChildItem; note how you must pass the variable name without the $ sigil to -OutVariable.

A small caveat is that -OutVariable, as of PowerShell [Core] 7.0:

  • collects multi-object output in a System.Collections.ArrayList instance rather than in a regular PowerShell array of type [object[]] (fixed-size array of System.Object instances).

  • even collects single-object output that way (wrapped in a collection) - whereas direct pipeline output just emits the object itself.

See this answer for background information and a workaround.

Sign up to request clarification or add additional context in comments.

1 Comment

Glad to hear it was helpful, @boblewis, and thanks for accepting and catching the typo - fixed now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.