【发布时间】:2021-12-16 13:36:55
【问题描述】:
我的脚本在 Powershell 5.x 上运行良好,但在 Powershell Core (7.2.1) 上不再运行
当我尝试拆分文本(从电子邮件复制并粘贴)时会出现问题..
这一切都归结为这部分代码:
$test="blue
green
yellow
"
#$test.Split([Environment]::NewLine)
$x = $test.Split([Environment]::NewLine)
$x[0]
$x[1]
在 Powershell 5 中,$x[0]==blue 和 $x[1]==green 的值
但在 Powershell Core 中,拆分没有任何作用,$x[1] 是“不存在的”。
在 Powershell 7 中,换行符的处理方式不同(至少我是这么认为的),但我找不到解决方案..
我尝试将代码更改为
$rows = $path.split([Environment]::NewLine) 和 $path.Split([System.Environment]::NewLine, [System.StringSplitOptions]::RemoveEmptyEntries) 但这并没有改变任何东西..
另外,当我使用“here-string”时
$test = @'
green
yellow
blue
white
'@
$x= $test -split "`r`n", 5, "multiline"
除了$x[0] 之外的所有内容都是空的(即$x[2])
在这里:powershell -split('') specify a new line
在这里:WT: Paste multiple lines to Windows Terminal without executing
到目前为止,我还没有找到解决问题的方法。
感谢任何帮助。
编辑:我发现了关于这个问题的提示,但还不明白它的含义:https://n-v-o.github.io/2021-06-10-String-Method-in-Powershell-7/
编辑 2: 感谢大家参与回答我的问题。 首先,我想我要写一个很长的解释,为什么我的问题与@SantiagoSquarzon 的重复答案不同。但是在阅读我的问题和另一个问题的答案时,我注意到我在做一些不同的事情..
显然我使用时有些不同
$splits = $test -split '`r?`n' # doesn't work in 5.1 and 7.2.1
$splits = $test -split '\r?\n' # works in 5.1 and 7.2.1 as suggested from Santiago and others
但是
$splits = $test.Split("\r?\n") # doesn't work in 5.1 and 7.2.1
$splits = $test.Split("`r?`n") # doesn't work in 5.1 and 7.2.1
$splits = $test.Split([char[]]"\r\n") # doesnt' work in 7.2.1
$splits = $test.Split([char[]]"`r`n") # works in 7.2.1
【问题讨论】:
-
您的第一个示例在 PS Core (Linux) 上运行良好。在你的第二个例子中尝试使用
-split "\r?\n" -
感谢您的回答。我在 Windows 10 (20H2) 上。 “`r`n”也有同样的问题
-
您的第一个示例在 PS7 上对我不起作用,但如果我使用
$test.Split("`n"),它确实有效。我认为其中一些行为会根据您的主机环境而有所不同(我的是 windows) -
-split "\r?\n"应该适用于所有情况,无论是 Windows / Linux / mac / PS Core / Win PS。 -
我明白了。如果您确实有 CRLF 换行符,请注意您自己答案中的解决方案以及最新编辑中的
$test.Split([char[]]"`r`n")将无法按预期工作,因为您将获得额外的空元素,表示每个 CR 和 LF 之间的空字符串序列,由于匹配这些字符。 个别。您的最新编辑还显示了关于您可以在哪里使用哪些转义序列以及在逐字与可扩展字符串中使用转义序列的误解 - 请参阅我的答案的更新。 /cc @SantiagoSquarzon
标签: powershell powershell-core