Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

powershell -split('') specify a new line

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

like image 410
colbyt Avatar asked Aug 30 '16 22:08

colbyt


People also ask

How do you make a new line in PowerShell?

Using PowerShell newline in Command To add newline in the PowerShell script command, use the` (backtick) character at the end of each line to break the command into multiple lines.

How do you add a line break in PowerShell?

Use `N to Break Lines in PowerShell You can use the new line `n character to break lines in PowerShell. The line break or new line is added after the `n character.

How do you write multiple lines in PowerShell?

To split long command into multiple lines, use the backtick (`) character in the command where you want to split it into multiple lines.

What is $_ in PowerShell script?

The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.


3 Answers

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.

like image 126
Ryan Ries Avatar answered Oct 10 '22 00:10

Ryan Ries


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
like image 23
LCC Avatar answered Oct 10 '22 02:10

LCC


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.

like image 16
aphoria Avatar answered Oct 10 '22 01:10

aphoria