Change Value Order in String

This topic contains 9 replies, has 4 voices, and was last updated by  Tore Groneng 1 year, 10 months ago.

  • Author
    Posts
  • #31499

    Chris Lindauer
    Participant

    I need some help on reordering my string value for ReverseDNS.

    Currently String: 75.20.24.10
    I want it to be: 10.24.20.75

    I tried use regex to switch the string in reverse but it does all the values:
    ex: 01.42.02.75

  • #31500

    Curtis Smith
    Participant

    split and then reassemble in reverse

    $IPOctects = "75.20.24.10" -split "\."
    $IP = "$($IPOctects[3]).$($IPOctects[2]).$($IPOctects[1]).$($IPOctects[0])"
    $IP
    10.24.20.75
    
  • #31501

    Chris Lindauer
    Participant

    Thanks Curtis, that's exactly what I was trying to accomplish

  • #31502

    Christian Sandfeld
    Participant

    Or split into an array, reverse the array, and join string again

    PS C:\> $String = '75.20.24.10'
    PS C:\> $String
    75.20.24.10
    
    PS C:\> $Array = $String.Split('.')
    PS C:\> [array]::Reverse($Array)
    PS C:\> $Reversed = $Array -join '.'
    
    PS C:\> $Reversed
    10.24.20.75
    
  • #31503

    Curtis Smith
    Participant

    Or

    $IP = "75.20.24.10".split(".")
    [array]::Reverse($IP)
    $IP -join "."
    10.24.20.75
    
  • #31504

    Curtis Smith
    Participant

    ah, bet me to the other option Christian 😀

  • #31505

    Christian Sandfeld
    Participant

    Found another interesting regex way here:
    https://social.technet.microsoft.com/Forums/windowsserver/en-US/5ec413b2-512f-47e1-9b42-0878f2269bf8/how-do-i-turn-this-string-into-the-reverse-desired-format-with-powershell?forum=winserverpowershell

    $String = '75.20.24.10'
    (New-Object RegEx '[^\.]+', 'RightToLeft').Matches($String) -join '.'
    
  • #31506

    Tore Groneng
    Participant

    I was actually going to suggest the reverse method also. However I got stuck for a couple of minutes due to the fact that the static reverse method does not return anything (void) and the signature does not suggest that is takes a [ref] variable ( static void Reverse(array array)). As it is a void, it should not return anything, however how does that work without [ref]?

  • #31507

    Chris Lindauer
    Participant

    Is there a way to have the input as a variable? Instead of a static entry of 75.20.24.10, the variable may contain more than one entry.

    $IPs = '75.20.24.10','76.20.24.10'

  • #31510

    Tore Groneng
    Participant

    but of course there is. Here is an advanced function that supports pipeline input as well:

    Cheers

    Tore

You must be logged in to reply to this topic.