user3214631
user3214631

Reputation: 43

Convert Raw/space delimited text to an array

I am working with RAW text file that I need to split and create an array. RAW Text file generated based on parameter. $list sent from another program. My Ps code:

param($list)
$path="C:\BU\test\"
New-Item $path\test.txt
Set-Content $path\test.txt "$list" --> Output RAW data Eg:(Apple Orange Kiwi)
$list2=get-Content C:\BU\test\test.txt
$cd=$list.Replace(' ',', ')   
New-Item $path\cd.txt
Set-Content $path\cd.txt "$cd"  
$cd=get-Content C:\BU\test\cd.txt  Output CD Data (Apple, Orange, Kiwi)

I am assuming If I call $cd[0] using write-host, Output should be Apple, but when I call $cd[0] gets only A. What am I missing ? thank you for suggestions.

Upvotes: 0

Views: 222

Answers (1)

mklement0
mklement0

Reputation: 437197

It looks like you're ultimately trying to do this, using the -split operator:

$list = 'Apple Orange Kiwi'
# Split $list into an array of tokens by whitespace.
$cd = -split $list # -> equivalent of @('Apple', 'Orange', 'Kiwi')

As for what you tried:

  • Get-Content by default reads files line by line.

  • Your input file contains just one line, containing verbatim Apple, Orange, Kiwi

  • Because of how PowerShell collects streaming output from commands, $cd=get-Content C:\BU\test\cd.txt stores that single line as a string in variable $cd, and not as an array containing that single line as its (only) element.

  • Indexing into a string returns the characters at the specified position(s), which is what you saw:

    $line = 'Apple, Orange, Kiwi'
    $line[0] # -> 'A', i.e. the *first character* of the string
    
    • To ensure that Get-Content always returns an array, you can use @(...), the array-subexpression operator:

      # $cd[0] then always returns the *first line*.
      $cd = @(Get-Content C:\BU\test\cd.txt)
      
    • Alternatively, type-constrain the receiving variable with [array]

      # [array] is the same as [object[]]
      [array] $cd = Get-Content C:\BU\test\cd.txt
      

See this answer for more information.

Upvotes: 2

Related Questions