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)
CodePudding user response:
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.
CodePudding user response:
If you don't pass -raw
parameter to Get-Content
cmdlet, the content is returned as an array of newline-delimited strings.