I’m trying to run a function that parses a large string that contains newlines, however whenever I pass this string into a function it gets rid of the new lines and makes it impossible to parse. Am I doing something wrong here?
function parseString([string] $s)
{
$result = $s | Select-String -pattern "foo"
return $result
}
If I type:
$s | Select-String -pattern "foo"
I get the correct result but using
parseString $s
returns the whole string with no newlines. Any suggestions?
EDIT: Hmm after messing around a bit I got rid of the [string] so it’s
function parseString($s)
This seems to work, but why?
What is
$s? If it is an array of string, then since you are saying thatparseStringtakes in a string, the array of string is converted into a string. If on the other hand$swere a single string, it will work ( as shown below):But if
$s=@("first line","secondline with foo","third line"), the array of strings is first converted to a string ( by simply joining each string ) and hence you will lose the newline. If you have got$s, fromGet-Contentetc. this will be the case.Note that, most of the times, you won’t need to specify the types in Powershell. Be it while assigning variables or in function paramaters.
PS:
If you did
you will get the expected result in the function with
[string].