`n" 扩展为仅 LF字符( Unix 样式,Unicode代码点 U + 000A ),但您的输入内容可能使用 CRLF序列(`r`n" , Windows -样式,Unicode代码将 U + 000D 和 U + 000A )作为换行符(换行符).>虽然给定的 platform 的本机换行符[sequence]反映在 [Environment] :: Newline 中,但不能保证给定的 input (文件)的换行符使用它.值得注意的是,脚本嵌入的此处字符串(例如, @< newline> ...< newline>" @ )使用封闭脚本文件以-和保存的任何换行格式.在读取脚本以执行脚本时,PowerShell在支持的 all 平台上都接受两者仅限LF和CRLF文件. 因此,用换行符将字符串分成几行的最可靠的形式是以下习惯用法,它利用了 -split 运算符默认接受的事实一个正则表达式作为分割条件: $ str -split'\ r?\ n'#返回$ str中包含的行数组 上面的代码可以正确处理仅使用LF( \ n )和CRLF( \ r \ n )换行符的输入,因为 \ r?\ n 与每个 \ n (LF)匹配,并且可选地(?)前面带有 \ r (CR).My question is very simple and I am very new to PowerShell but I'm just wondering if there is a easy way to split a string by each line and add the contents of each line into a separate array entry. 解决方案 To complement Don Cruickshank's helpful answer:"`n" expands to a LF character only (Unix-style, Unicode code point U+000A), but your input may use CRLF sequences ("`r`n", Windows-style, Unicode code points U+000D and U+000A) as newlines (line breaks).While a given platform's native newline character [sequence] is reflected in [Environment]::Newline, there's no guarantee that a given input (file)'s newlines uses it.Notably, script-embedded here-strings (e.g., @"<newline>...<newline>"@) use whatever newline format the enclosing script file was saved with - and when reading scripts for execution, PowerShell accepts both LF-only and CRLF files on all platforms it supports.Therefore, the most robust form to split a string into lines by newlines is the following idiom, which takes advantage of the fact that the -split operator by default accepts a regular expression as the split criterion: $str -split '\r?\n' # returns array of lines contained in $strThe above handles input with both LF-only (\n) and CRLF (\r\n) newlines correctly,because \r?\n matches each \n (LF) optionally (?) preceded by an \r (CR). 这篇关于如何在每一行中将字符串拆分并将每行放入PowerShell中的单独数组条目中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 11-01 16:36