0

In a cmd window I search for a specific file then pass it into an executable. I want to redo this using PowerShell, with similar constraints on being on a single line or two independent and separate lines, but being new I can't figure it out.

 cmd /r dir /s /b RunnerUnitTest.dll | findstr /r bin\\ > tests_list.txt
 cmd /r for /f %f in (tests_list.txt) do vstest.console.exe "%f"

The first command looks for a file, it finds two:

RunnerUnitTest\bin\Debug\RunnerUnitTest.dll

RunnerUnitTest\obj\Debug\RunnerUnitTest.dll

then it narrows it down to one (bin in the path) and sticks it into a file:

RunnerUnitTest\bin\Debug\RunnerUnitTest.dll

The second line takes this output and passes it into an executable as a parameter.

This is for a gitlab runner, btw

Neil
  • 357
  • 2
  • 10

1 Answers1

2

You can do something like this without an intermediate file, since Get-ChildItem will return a FileInfo object for files, and DirectoryInfo objects for directories (both of which are derived from FileSystemInfo):

Get-ChildItem -Recurse bin\Debug\RunnerUnitTest.dll | Select-Object -First 1 | Foreach-Object {
  vstest.console.exe $_.FullName
}

What this will do is recursively search for all files found named RunnerUnitTest.dll with parent folders Debug and bin, and then for each file returned (I've added a Select-Object -First 1 to ensure we only get one assembly back but this is optional) pass the full path to the assembly to the vstest.console.exe program.

The way it's written above, the assembly under the obj folder won't be returned at all for execution consideration.


As an FYI, piping with | works much in the same way as it does with other shells like Bash or cmd, but it supports passing around complex objects instead of strings. As a general rule, you can pipe any output on the output stream to other cmdlets or save the output to variables. Redirection operators work similarly as well.

codewario
  • 19,553
  • 20
  • 90
  • 159
  • Superb thanks. Works a treat. The only 'issue' but I can live with it is my old code didn't need the path to the file putting in, i could just put a search word, e.g. 'bin' and it would find the right one. – Neil Apr 23 '20 at 08:38
  • Sure, but what happens when you also have a Release build or some other named build configuration also existing under the `bin` folder? Which one will it pick? – codewario Apr 24 '20 at 15:20