Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PS .Contains() method does not work on Get-Content return object

I tried to use the .Contains() method to check if a file contains a certain string:

# $file content: 123
$content = Get-Content -Path $file

$content.Contains("1") # Is always false, why?
"$content".Contains("1") # Works

Why are the " required so that the .Contains method works?

$content | Get-Member


   TypeName: System.String

Name             MemberType            Definition                                                                                       
----             ----------            ----------                                                                                       
(...)
Contains         Method                bool Contains(string value)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As commented, using Get-Content returns an array of lines.
By quoting that result "$content" PowerShell merges these single lines together into a single string and then the String’s method .Contains() works as expected.

If you add switch -Raw to the Get-Content statement, the result is a single multiline string on which the .Contains() method works.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading