PowerShell Split String by Comma [5 Simple Methods That Actually Works]

Working with comma-separated values is something I do almost daily in my PowerShell scripts. Mostly, you will get requirements in situations such as parsing CSV files, handling API responses, or processing user inputs.

In this tutorial, I’ll show you five different methods to split strings by comma in PowerShell with practical examples.

Method 1 – Using the Split() Method

The simplest and most common way to split a string by a comma in PowerShell is using the Split() method. This is my go-to approach for straightforward string splitting.

Here’s how it works:

$csvString = "New York,Los Angeles,Chicago,Houston,Phoenix"
$cities = $csvString.Split(",")

# Display the result
$cities

Output:

New York
Los Angeles
Chicago
Houston
Phoenix

You can see the exact output in the screenshot below:

PowerShell Split String by Comma

The Split() method returns an array containing the substrings created by splitting the original string at each comma. This method is clean, efficient, and works great for simple comma-separated values.

You can also specify multiple delimiters:

$mixedString = "New York,Los Angeles;Chicago|Houston,Phoenix"
$cities = $mixedString.Split(",", ";", "|")

# Display the result
$cities

Output:

New York
Los Angeles
Chicago
Houston
Phoenix

Check out Split String by Tab Character in PowerShell

Method 2 – Using the -split Operator

PowerShell provides a dedicated -split operator that offers more flexibility than the Split() method. This is particularly useful when working with complex patterns or when you need case-insensitive splitting.

$csvString = "New York,Los Angeles,Chicago,Houston,Phoenix"
$cities = $csvString -split ","

# Display the result
$cities

You can see the exact output in the screenshot below:

Split String by Comma PowerShell

The output is identical to our first example, but the -split operator gives us additional capabilities:

Case-Insensitive Splitting

$mixedCase = "Apple,BANANA,orange,GrApE"
$fruits = $mixedCase -isplit "a"

# Display the result
$fruits

Output:

pple,B
N
N
,or
nge,Gr
pE

Using Regular Expressions

The -split operator also supports regular expressions, which is extremely powerful:

$complexString = "New York, Los Angeles,  Chicago , Houston,Phoenix"
$cities = $complexString -split ",\s*"

# Display the result
$cities

Output:

New York
Los Angeles
Chicago
Houston
Phoenix

The pattern ,\s* splits on commas followed by zero or more whitespace characters, handling inconsistent spacing in your data.

Check out Split Large Text Files with PowerShell

Method 3 – Using the Split-String Function

For more complex scenarios, I often create a custom function to handle string splitting with additional processing:

function Split-String {
    param (
        [Parameter(Mandatory=$true)]
        [string]$InputString,

        [string]$Delimiter = ",",

        [switch]$Trim,

        [switch]$RemoveEmptyEntries
    )

    $result = $InputString -split $Delimiter

    if ($Trim) {
        $result = $result | ForEach-Object { $_.Trim() }
    }

    if ($RemoveEmptyEntries) {
        $result = $result | Where-Object { $_ -ne "" }
    }

    return $result
}

# Example usage
$messyData = " New York , , Los Angeles, Chicago ,, Houston "
$cities = Split-String -InputString $messyData -Trim -RemoveEmptyEntries

# Display the result
$cities

Output:

New York
Los Angeles
Chicago
Houston

You can see the exact output in the screenshot below:

Split String by Comma in PowerShell

This function allows us to handle messy data by optionally trimming whitespace and removing empty entries, which is very common when dealing with real-world data.

Check out Split Path Into Array In PowerShell

Method 4 – Using ConvertFrom-Csv for Structured Data

When working with more structured CSV data that includes headers, PowerShell’s ConvertFrom-Csv cmdlet is incredibly powerful:

$csvData = @"
City,State,Population
New York,NY,8336817
Los Angeles,CA,3979576
Chicago,IL,2693976
Houston,TX,2320268
Phoenix,AZ,1680992
"@

$cities = $csvData | ConvertFrom-Csv

# Display the result as a table
$cities | Format-Table

# Access specific columns
$cities | ForEach-Object { "$($_.City), $($_.State): $($_.Population) people" }

Output:

City         State Population
----         ----- ----------
New York     NY    8336817
Los Angeles  CA    3979576
Chicago      IL    2693976
Houston      TX    2320268
Phoenix      AZ    1680992

New York, NY: 8336817 people
Los Angeles, CA: 3979576 people
Chicago, IL: 2693976 people
Houston, TX: 2320268 people
Phoenix, AZ: 1680992 people

This approach is perfect when dealing with structured data as it automatically creates objects with properties based on the CSV headers.

Check out Split an Array into Smaller Arrays in PowerShell

Method 5 – Using Import-Csv for Files

When your comma-separated data is stored in files, the Import-Csv cmdlet is the way to go:

# Assuming we have a cities.csv file with the data from the previous example
$cities = Import-Csv -Path "cities.csv"

# Filter cities with population over 3 million
$largeCities = $cities | Where-Object { [int]$_.Population -gt 3000000 }

# Display large cities
$largeCities | Format-Table

Output:

City         State Population
----         ----- ----------
New York     NY    8336817
Los Angeles  CA    3979576

The Import-Csv cmdlet handles all the file opening and string splitting for you, making it extremely convenient for file-based operations.

Check out Split Strings into Arrays in PowerShell

Handle Special Cases

Now, let me show you some exceptional cases that we can use while spelling a string with a comma in PowerShell.

Dealing with Quoted Commas

Sometimes, commas appear within quoted strings and shouldn’t be used as delimiters:

$complexCsv = 'Chicago,IL,"Windy City, Second City",2693976'

# Simple split won't work correctly
$badSplit = $complexCsv -split ","
$badSplit

# Use regex for proper CSV parsing
$pattern = ',(?=(?:[^"]*"[^"]*")*[^"]*$)'
$goodSplit = $complexCsv -split $pattern
$goodSplit

Output:

# Bad split (splits inside quotes)
Chicago
IL
"Windy City
 Second City"
2693976

# Good split (preserves commas inside quotes)
Chicago
IL
"Windy City, Second City"
2693976

The regular expression used here is complex but powerful – it only splits on commas that aren’t inside double quotes.

Escaping Commas

Another approach is to properly handle escaped commas in PowerShell.

$escapedCsv = 'Chicago,IL,Windy City\, Second City,2693976'

function Split-EscapedCsv {
    param ([string]$Input)

    $result = @()
    $current = ""
    $escaped = $false

    foreach ($char in $Input.ToCharArray()) {
        if ($escaped) {
            $current += $char
            $escaped = $false
        }
        elseif ($char -eq '\') {
            $escaped = $true
        }
        elseif ($char -eq ',') {
            $result += $current
            $current = ""
        }
        else {
            $current += $char
        }
    }

    # Add the last field
    $result += $current
    return $result
}

Split-EscapedCsv -Input $escapedCsv

Output:

Chicago
IL
Windy City, Second City
2693976

This function manually processes each character, handling escape sequences correctly.

Read Remove the Last Empty Line from a File Using PowerShell

Best Practices for Splitting Strings

Based on my experience, here are some best practices when splitting strings in PowerShell:

  1. Choose the right method for your data complexity:
    • Use Split() or -split for simple cases
    • Use ConvertFrom-Csv for structured data with headers
    • Use custom parsing for complex cases with quotes or escapes
  2. Always validate your data:
    • Check for unexpected empty entries
    • Handle leading/trailing whitespace
    • Be prepared for inconsistent delimiters
  3. Consider performance for large datasets:
    • String operations can be memory-intensive
    • Process large files in chunks rather than loading everything into memory
    • Use streaming approaches when possible
  4. Document your approach:
    • Add comments explaining regex patterns
    • Document any assumptions about the input format

PowerShell offers multiple approaches to split strings by a comma. For simple cases, the built-in Split() method or -split operator will serve you well. For more complex scenarios involving structured data, the ConvertFrom-Csv and Import-Csv cmdlets provide powerful options.

I hope you found this tutorial helpful! If you have any questions about splitting strings in PowerShell, feel free to leave them in the comments below.

Other PowerShell tutorials you may also like:

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

FREE Download an eBook that contains 100 PowerShell cmdlets with complete script and examples.