What’s the difference between -split and .split() in PowerShell?

Here’s a question I see over and over and over again: “I have a string and I’m trying to split it on this part, but it’s jumbling it into a big mess. What’s going on?” Well, there’s splitting a string in PowerShell, and then there’s splitting a string in PowerShell. Confused? Let me explain.

Say you have this string for our example.

Now let’s say you want to split it on all the “s” characters. You might do this and get these results.

That did exactly what we thought it would. It took our string and broke it apart on all the “s”‘s. Now, what if I want to split it where there’s an “st”? There’s only two spots it should split: the “st” in “interesting” and in “string”. Let’s try the same thing we tried before.

Well that ain’t right. What happened? If we look closely, we can see that our string was split anywhere that there was an “s” or a “t”, rather than where there was an “st” together.

.split() is a method that takes an array of characters and then splits the string anywhere it sees any of those characters.

-split is an operator that takes a pattern string (regular expression) and splits the string anywhere it sees that pattern.

Here’s what I should have done to split our string anywhere there’s an “st”.

That looks more like we’re expecting.

Remember, .split() takes an array of characters, -split takes a string.

Leave a Reply

Your email address will not be published. Required fields are marked *