powershell -split('') specify a new line

2020-06-30 06:31发布

问题:

Get-Content $user| Foreach-Object{
   $user = $_.Split('=')
   New-Variable -Name $user[0] -Value $user[1]}

Im trying to work on a script and have it split a text file into an array, splitting the file based on each new line

What should I change the "=" sign to

回答1:

It depends on the exact encoding of the textfile, but [Environment]::NewLine usually does the trick.

"This is `r`na string.".Split([Environment]::NewLine)

Output:

This is

a string.



回答2:

The problem with the String.Split method is that it splits on each character in the given string. Hence, if the text file has CRLF line separators, you will get empty elements.

Better solution, using the -Split operator.

"This is `r`na string." -Split "`r`n" #[Environment]::NewLine, if you prefer


回答3:

You can use the String.Split method to split on CRLF and not end up with the empty elements by using the Split(String[], StringSplitOptions) method overload.

There are a couple different ways you can use this method to do it.

Option 1

$input.Split([string[]]"`r`n", [StringSplitOptions]::None)

This will split on the combined CRLF (Carriage Return and Line Feed) string represented by `r`n. The [StringSplitOptions]::None option will allow the Split method to return empty elements in the array, but there should not be any if all the lines end with a CRLF.

Option 2

$input.Split([Environment]::NewLine, [StringSplitOptions]::RemoveEmptyEntries)

This will split on either a Carriage Return or a Line Feed. So the array will end up with empty elements interspersed with the actual strings. The [StringSplitOptions]::RemoveEmptyEntries option instructs the Split method to not include empty elements.