Search code examples
powershell

Split and Join is resulting in error when I run it in a FOREACH block


I have a set of data inside a variable $pods similar to the below.

Orange-UK-1234567890-de22a
Orange-US-123456-svbf3
Blue-US-NA-123456789-fr33s

With this data, I am trying to get rid of any characters after the second from the right '-' hyphen. This is the code I am using and it is successful if I pass only one value.

$onepod = 'Orange-UK-1234567890-de22a'
$onepod.split('-')[-5..-3] -join '-'

However, if I pass this into a foreach, as below, it doesn't work

foreach ($onepod in $pods)
{$onepod.split('-')[-5..-3] -join '-'}

I get the error below:

Method invocation failed because [Microsoft.Powershell.Commands.MatchInfo] does not contain a method named 'split'

Basically, all I need is to exclude all character after the second FROM THE RIGHT hyphen including that hyphen, to return the below:

Orange-UK
Orange-US
Blue-US-NA

Is anyone able to advise please?

Thanks in advance!


Solution

  • You could use the regex replacement operator (-replace) for this. See https://regex101.com/r/5G1kRG/2 for regex details.

    $pods = @(
        'Orange-UK-1234567890-de22a'
        'Orange-US-123456-svbf3'
        'Blue-US-NA-123456789-fr33s')
    
    $pods -replace '(?:-[^-]+){2}$'
    
    # Orange-UK
    # Orange-US
    # Blue-US-NA