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
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.
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.
To split long command into multiple lines, use the backtick (`) character in the command where you want to split it into multiple lines.
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.
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.
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
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.
$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
.
$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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With