In this article, I have mentioned the PowerShell script to split a string into an array with an example. Before we begin to convert a string into an array, let me introduce you to what is an array in PowerShell.

Arrays are the fixed-sized, sequentially ordered collection of the elements of any data type. We can create and print an array in PowerShell as below

$Array="Vikram","Vijay","Vinod","Vikas"
$Array

Output, will print array values

Vikram
Vijay
Vinod
Vikas

split-string-into-array-powershell

Now, We can convert a string into an array or you can say split string into array by delimiter in PowerShell using 2 ways:

  1. Using .Split()
  2. Using .ToCharArray()

We will see its examples, one by one.

Using .Split()

We can use the split operator (-Split) to split a string text into an array of strings or substrings.

$String = "Hello, this is, simple string"
$ArrayOfString = $String -split ","
$ArrayOfString

Output:

Hello
 this is
 simple string

split-string-into-array-powershell-method

OR

We can also use .Split() instead of "-Split", as shown below

$Inputstring ="ASP-NET-Core"
$Array =$InputString.Split("-")
$Array

Output

ASP
NET
Core

By default, the function splits the string based on the whitespace characters like space, tabs, and line-breaks.

Using .ToCharArray() function

The .ToCharArray() function copies the characters of the string into the Unicode character array, so you can say instead of dividing large string into smaller chunks of string, it converts string into characters.

$Inputstring ="Hello World"
$Array =$InputString.ToCharArray()
$Array

Will give output as

H
e
l
l
o

W
o
r
l
d

In the above PowerShell script, the $InputString variable contains the string value.

Then, we have used ToCharaArray() string method to convert a string to an array, which returns a character array.

Once we have saved character array in $Array, we print it.

You may also like to read:

How to Check Installed Powershell Version