nixgeek
nixgeek

Reputation: 61

Powershell convert string to array

How do I change:

$Text = "Apple Pear Peach Banana"

to

$Text = @("Apple", "Pear", "Peach", "Banana")

I am planning to feed the array to a foreach loop. The input the user is prompted to enter fruit with a space between (I will use Read-Host for that). So then I need to convert a space-separated string to an array for the foreach loop.

Thank you...

Upvotes: 6

Views: 30499

Answers (4)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174465

I would use the -split regex operator, like so:

$text = -split $text

You can also use it directly in the foreach() loop declaration:

foreach($fruit in -split $text)
{
    "$fruit is a fruit"
}

In unary mode (like above), -split defaults to splitting on the delimeter \s+ (1 or more whitespace characters).

This is nice if a user accidentally enters consecutive spaces:

PS C:\> $text = Read-Host 'Input fruit names'
Input fruit names: Apple Pear   Peaches  Banana
PS C:\> $text = -split $text
PS C:\> $text
Apple
Pear
Peaches
Banana

Upvotes: 11

Jeff Zeitlin
Jeff Zeitlin

Reputation: 10764

$text = $text -split " "

will work, provided that none of your fruit names are two words that you want to keep together.

Upvotes: 1

ArcSet
ArcSet

Reputation: 6860

Use Split()

$text = $text.Split(" ")

Upvotes: 2

thepip3r
thepip3r

Reputation: 2935

$Text.Split(' ')

need more characters for answer.

Upvotes: 0

Related Questions