I'm trying to split a txt doc in Powershell based on a New Line. The script worked okay when splitting on a ',' but now I've changed it to use [Environment]::NewLine it only seems to be picking the last line up.
This is the part of the script that should be splitting by newline:
Get-Content C:\Bindings.txt | Foreach-Object{ $hostHeaders = $_.Split([Environment]::NewLine, [StringSplitOptions]::RemoveEmptyEntries) }The .txt document looks like so:
http:*:80:test.com
http:*:80:test2.com
http:*:80:test1.comAny ideas on how I can make it split on the New Line and not only see the last line or am I missing something?
2 Answers
I've 3 methods for you
I've prepared a .txt file
(Get-Content C:\temp\Bindings.txt)
http:*:80:test.com
http:*:80:test2.com
http:*:80:test1.comAnd now 3 methods
(Get-Content C:\temp\Bindings.txt) -split"`r`n"
(Get-Content C:\temp\Bindings.txt) -split "[Environment]::NewLine"
(Get-Content C:\temp\Bindings.txt).Split([Environment]::NewLine, [StringSplitOptions]::RemoveEmptyEntries)the result is like this
http:*:80:test.com
http:*:80:test2.com
http:*:80:test1.com You don't need to do anything. The default behavior of Get-Content with a text file is to split on the new-line and return an array of strings:
PS C:\...\Can Delete 3>Get-Content data.txt
http:*:80:test.com
http:*:80:test2.com
http:*:80:test1.com
PS C:\...\Can Delete 3>$object = Get-Content data.txt
PS C:\...\Can Delete 3>$object.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
PS C:\...\Can Delete 3>$object.count
3
PS C:\...\Can Delete 3>$object[0]
http:*:80:test.com
PS C:\...\Can Delete 3>$Object | Get-Member TypeName: System.String
Name MemberType Definition
---- ---------- ----------
...