Powershell 摆脱函数中的换行符
我正在尝试运行一个函数来解析包含换行符的大字符串,但是每当我将此字符串传递给函数时,它都会删除新行并使其无法解析。我在这里做错了什么吗?
function parseString([string] $s)
{
$result = $s | Select-String -pattern "foo"
return $result
}
如果我输入:
$s | Select-String -pattern "foo"
我得到正确的结果,但使用
parseString $s
返回整个字符串,没有换行符。有什么建议吗?
编辑:嗯,经过一番混乱之后,我摆脱了 [string],所以这
function parseString($s)
似乎有效,但为什么呢?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
什么是
$s
?如果它是一个字符串数组,那么由于您说parseString
接受一个字符串,因此该字符串数组将转换为字符串。另一方面,如果$s
是单个字符串,它将起作用(如下所示):但是如果
$s=@("first line","secondline with foo","第三行”)
,字符串数组首先被转换为字符串(通过简单地连接每个字符串),因此您将丢失换行符。如果您从Get-Content
等获得了$s
,情况就会如此。请注意,大多数时候,您不需要在 Powershell 中指定类型。无论是在分配变量时还是在函数参数中。
PS:
如果您这样做,
您将在带有
[string]
的函数中获得预期结果。What is
$s
? If it is an array of string, then since you are saying thatparseString
takes in a string, the array of string is converted into a string. If on the other hand$s
were 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-Content
etc. 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]
.删除
[string]
可能会删除正在发生的转换。您可以通过这种方式将对象类型转换为其他类型。例如:输出:System.Int32
输出:System.String
如果您的输入是字符串数组,
[string]
会将其转换为单个字符串,如-join
操作员。要查看发生了什么,请在调用函数之前和函数内部打印出
$YourVariable.GetType().FullName
(仍然使用[string]
)。Removing
[string]
is probably removing the cast that is happening. You can cast object types to other types this way. For example:Output: System.Int32
Output: System.String
If your input is a string array,
[string]
will cast it to a single string, like the-join
operator.To see what is happing, print out
$YourVariable.GetType().FullName
before calling the function and inside the function (still using[string]
).