Search code examples
powershell-3.0

Split String in Powershell at every occurence of an @ and save substrings


I have a string that might change depending to input in a gui. The string looks like this "@Donald @Trump @is @orange @and ...) So I have n Substrings that i want to split up and save like this: $word1 = "Donald" $word2 = "Trump".... $wordn = "xy" and I also need the value of n.


Solution

  • The PowerShell -split operator will do what you want, except that instead of each substring being in a separate variable, they'll be in an array. Using your example,

    $words = "@Donald @Trump @is @orange" -split "@"
    

    will give you an array, where $words.length will be 5, and the words will be in $words[1] through $words[4] (with $words[0] being the empty string).

    SS64 has good information on -split; so does Microsoft Docs.