Is there a way to output specific lines of code from a content using PowerShell?

I have used the code below to get all lines from content $ProjectFileContents that has "<PackageReference Include"

$ProjectFileContents | Find "<PackageReference Include" | Sort-Object -Unique

However when I try to get another line from the same content $ProjectFileContents that has "<OutputType", it returns an error

$ProjectFileContents | Find "<PackageReference Include" | Sort-Object -Unique

Error Gotten

Find : FIND: Parameter format not correct
At line:1 char:24
+ $ProjectFileContents | Find "OutputType" | Sort-Object -Unique
+                        ~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (FIND: Parameter format not correct:String) [], 
RemoteException
+ FullyQualifiedErrorId : NativeCommandError

I have used the same format I used initially however does not work for different set of strings. Any help will be appreciated. Thanks!!.


Solution 1:

tl;dr

Use --%, the stop-parsing token to satisfy find.exe's specific quoting requirements.

$ProjectFileContents | find.exe --% "OutputType" | Sort-Object -Unique

As an aside: As Lee_Dailey recommends, consider a PowerShell-only solution, with Select-String, which would bypass your problem.

The problem is that find.exe has very specific quoting requirements (which findstr.exe doesn't have, so it is another alternative to consider): The search term must always be enclosed in "...", whether it contains spaces or other metacharacters or not.

However, when PowerShell rebuilds the command line to ultimately use behind the scenes, it only double-quotes on demand, so that a verbatim argument such as OutputType - because it contains no spaces - is passed as-is, without quoting - even if it was originally quoted in the PowerShell command.

--% tells PowerShell to retain the remaining arguments as-is, which preserves the "..." quoting - but do note that the remaining arguments mustn't contain variable references, as they wouldn't be expanded.

See the bottom section of this answer for a detailed discussion of the limitations and pitfalls associated with --%