How Do I Split a String by ‘ – ‘ in PowerShell?

0
4
Asked By CleverTaco99 On

Hey everyone! I have a filename that looks like this:
C - 2025-03-18 - John Doe - (Random info) - Jane Dane.pdf.
I'm trying to figure out how to split this string every time it encounters " - " (space, dash, space). I thought using `$test.split(" - ")` would do the trick, but it doesn't seem to be working as I expected. Any help would be greatly appreciated!

2 Answers

Answered By CodeMaster5000 On

You can also try this method:

"C - 2025-03-18 - John Doe - (Random info) - Jane Dane.pdf".Split(" - ")

And the output would be:

C
2025-03-18
John Doe
(Random info)
Jane Dane.pdf

So, what exactly were you expecting it to do? More info could help!

CleverTaco99 -

Thank you for your swift response. Apparently my work is using an older Powershell. purplemonkeymad provided my solution.

PowerShellWizard -

Just to note, PowerShell 5.1 doesn't support all the overloads of `string.split`. If you upgrade to PowerShell 7, you can use it with a string as a delimiter, which makes it much simpler.

Answered By purplemonkeymad On

If you're using Windows PowerShell 5.1 or earlier, the `split()` method works differently than you might expect. It doesn't take a string for the delimiter, but an array of characters. Instead, you can use the `-split` operator like this:

$test -split ' - '

This should work properly on all versions of PowerShell! Just be cautious with regex characters if your string contains any.

CleverTaco99 -

This was it. Very much appreciated. Thank you for your swift response.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.