Arrays are one of the most useful data structures in PowerShell. They allow you to store multiple values in a single variable, making it easy to organize and access your data.
In this comprehensive guide, we‘ll cover everything you need to know about using arrays of strings in PowerShell, including:
- What is an array of strings
- Creating arrays of strings
- Accessing and manipulating string arrays
- Common operations like appending, sorting, slicing etc.
- Special considerations when working with string arrays
Let‘s get started!
What is a String Array in PowerShell?
A string array is simply an array where each element is a string value instead of another data type like integer, boolean etc.
Arrays can hold any .NET object, and strings are valid .NET objects. So you can create arrays that only hold string values.
Here‘s an example of a simple string array in PowerShell:
$stringArray = "Hello", "World", "from", "PowerShell"
This array contains 4 string elements. We can verify it‘s an array of strings by checking its type:
$stringArray.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
The base type System.Array confirms it‘s an array. And the type itself Object[] tells us it‘s an array of .NET objects, which includes strings.
Why Use a String Array?
String arrays are extremely common in most programming languages, as text manipulation is a frequent task.
Here are some common scenarios where a string array can be useful in PowerShell:
- Storing a list of names, paths, keywords etc.
- Temporarily storing pieces of text before processing
- Passing multiple string arguments to a function
- Reading output from an external command
- Gathering related pieces of data together
Essentially whenever you need to work with multiple string values, use a string array to keep things tidy and accessible.
Next, let‘s go through different ways to create string arrays in PowerShell.
Creating a String Array
There are a few different syntaxes available for creating an array of strings in PowerShell:
1. Array Sub-Expression @()
The easiest way is to use PowerShell‘s array sub-expression operator @(). This allows you to quickly initialize a string array:
$stringArray = @("apple", "banana", "mango")
We simply pass our string values inside @() and PowerShell automatically creates the array.
2. Array Constructor
Another approach is to use the array constructor syntax:
$stringArray = [string[]]("peach", "plum", "pear")
Here we explicitly create a string[] array type and pass our 3 fruit strings during initialization.
3. Casting a String as an Array
You can also cast a delimited string as an array directly.
For example:
[string[]] $fruits = "apple,banana,orange" -split ","
We take a comma delimited string, split it on , which returns a string array by default. And cast that as string[] to ensure we get back a string array.
The key thing to note is PowerShell makes it really convenient to create string arrays on the fly.
Next let‘s see how to manipulate them.
Accessing String Arrays
To access a string array you use indexing just like with standard arrays:
$fruits = @("apple", "banana", "orange")
$fruits[0] # Access first element
$fruits[1] # Access second element
So $fruits[0] would give us apple and so on.
You can also get the total number of elements using the .Length property:
$fruits.Length # Outputs 3
And iterate over all elements with foreach:
foreach ($fruit in $fruits) {
Write-Output "Fruit: $fruit"
}
This prints:
Fruit: apple
Fruit: banana
Fruit banana
So standard array access techniques apply as you‘d expect.
Now let‘s look at some useful ways for working with string arrays.
Useful String Array Operations
Here I‘ll demonstrate some helpful operations when working with arrays of strings:
Append to a String Array
You can append additional strings to an array using the addition assignment += operator:
$fruits += "grapes", "mango"
That appends those two new elements to the $fruits array.
Check if Array Contains Value
To check if a string array contains a particular value, use .Contains():
$fruits.Contains("apple") # True
Combine Two String Arrays
Use the addition operator + to combine two existing string arrays:
$fruits = @("apple", "banana")
$veggies = @("corn", "potato")
$produce = $fruits + $veggies
Now $produce contains all the elements from both arrays.
Get Array Length
Retrieve the number of elements with .Length:
$produce.Length # 4 elements
Sort a String Array
Sort your string array alphabetically:
$sortedFruits = [string] $fruits
$sortedFruits.Sort()
$sortedFruits
apple
banana
grapes
mango
orange
We have to explicitly cast as [string] here. But now the fruits are sorted nicely!
Loop Through String Array
Iterate using foreach:
foreach ($fruit in $fruits) {
Write-Output "I love $fruit"
}
This will output each fruit individually.
So in summary, all the usual array operations are available. Strings arrays aren‘t treated specially in any way.
Now let‘s go through some key differences to be aware of when working with string arrays.
Strings vs String Arrays: Key Differences
It‘s important to understand strings and string arrays are not interchangable:
| Strings | String Arrays |
|---|---|
| . Single value | Zero or more elements |
| . Immutable | Mutable – can add/remove elements |
| . Simple text manipulation | Designed for complex data operations |
| . Accessed via index or substring | Accessed via numeric index |
So while strings and string arrays both ultimately contain textual data, how you should use them depends on your specific needs:
- For simple text manipulation tasks, use regular PowerShell strings and its built-in string methods for performance.
- For more complex data tasks like gathering, filtering, sorting strings – use string arrays.
The same PowerShell code may manipulate a single string vs string array differently.
For example, appending to a string Simple concatenation:
$string1 = "Hello"
$string1 += " World"
But for string arrays, multi-value append:
$array = @("Hello")
$array += "World"
So keep this distinction in mind.
Alright, next let‘s go over some best practices when working with string arrays in PowerShell.
String Array Best Practices
Here are some tips for working with arrays of strings efficiently:
Initialize Once
Initialize your string arrays only once rather than overwriting:
✅ Good:
$urls = @()
$urls += "https://microsoft.com"
$urls += "https://docs.microsoft.com/"
❌ Avoid:
$urls = @("https://microsoft.com")
$urls = @("https://microsoft.com","https://docs.microsoft.com/")
Constantly re-declaring will create unnecessary arrays and overwrite.
Know When to Sort
Arrays of strings have an overhead cost to sort. Only sort when explicitly needed rather than by default.
❌ Avoid:
$fruits = @("apple", "banana", "orange")
$sortedFruits = [string] $fruits
$sortedFruits.Sort()
# Unnecessary sort!
✅ Good:
$fruits = @("apple", "banana", "orange")
if ($SortFruits) {
$sortedFruits = [string[]] $fruits
$sortedFruits.Sort()
}
# Only sort when needed
Use ArrayList for Dynamic Arrays
If you need to dynamically add and remove elements from an array frequently, use an ArrayList instead of a standard array:
$list = New-Object System.Collections.ArrayList
$list.Add("Start") | Out-Null
$list.Add("Middle") | Out-Null
$list.Remove("Start") | Out-Null
$list # Contains only "middle"
ArrayLists adjust size automatically whereas arrays have fixed capacity.
Avoid Unnecessary Casting
Avoid unnecessary array casting which can reduce performance:
❌ Avoid:
$fruits = [string[]]@("apple", "banana")
# Unnecessary string[] cast!
✅ Good:
$fruits = @("apple", "banana")
# No need to cast array
So in summary – initialize once, sort only when required, use ArrayLists dynamically and avoid pointless casting. Keeping these best practices in mind will optimize your code.
Putting it All Together
Let me demonstrate string arrays in action by manipulating website domains:
# Start with array of raw URLs
$urls = @(
"https://docs.microsoft.com",
"https://powershell.org/forums/",
"https://stackoverflow.com/questions/tagged/powershell"
)
# Extract root domains
$domains = $urls | ForEach-Object {
$_.Substring($_.IndexOf("//")+2) # Get substring after //
} | ForEach-Object {
$_.Split("/")[0] # Get part before first /
}
# Get top level domains
$tlds = $domains | ForEach-Object {
$_.Split(".")[-1] # Just grab last section
}
# Remove duplicates
$uniqueTlds = $tlds | Select-Object -Unique
# Count occurrences
$tldCounts = @{}
foreach ($tld in $tlds) {
$tldCounts[$tld]++
}
"Unique TLDs: $($uniqueTlds.Count)"
$tldCounts
This outputs:
Unique TLDs: 2
Name Value
com 2
org 1
Here‘s what it‘s doing step-by-step:
- Starts with string array
$urlscontaining page URLs - Extracts domain from each URL using substring
- Splits on slash to extract root domain into
$domains - Splits on dot (.) to extract top level domain into
$tlds - Gets unique TLDs and counts occurrence per TLD
And we use a combination of pipelines, loops, subscripting and hashtables to piece it all together!
This demonstrates how easily string arrays let you gather, split, filter and analyze textual data.
So in this example we transformed a simple list of URLs all the way down to usage statistics on their TLDs using the power of string arrays.
Alright, that wraps up this guide on manipulating arrays of strings with PowerShell!
Summary
Key points about string arrays in PowerShell:
- A string array holds multiple string values within a single variable
- Common ways to create are
@(), array constructor or splitting strings - Standard array indexing and iteration work as expected
- Useful operations: append, combine, sort strings
- Distinct from regular PowerShell strings for text manipulation
- Good practices: initialize once, only sort when required, use ArrayLists dynamism
So in this article we covered the basics of string arrays – how to create them, access elements, manipulate them and good habits to build.
I hope this gives you a solid grasp of PowerShell string arrays. They open up all sorts of text processing capabilities.
Feel free to reach out with any other array-related topics for future guides!


