Get-random characters from one long word/string?

This topic contains 5 replies, has 3 voices, and was last updated by  random commandline 4 months, 2 weeks ago.

  • Author
    Posts
  • #90721

    Alexander Holmeset
    Participant

    How can i for example choose to get 10 difrent random characters from a long string/word?
    String example: "asdfadfnglkaslkngalkfnk2342419!1342@sadfadsfad?123412341adfafa"

  • #90722

    Jeremy Corbello
    Participant
    $string = "asdfadfnglkaslkngalkfnk2342419!1342@sadfadsfad?123412341adfafa"
    
    for ($i = 0; $i -lt 10; $i++ ) {
        $newString += $string[(Get-Random -Minimum 0 -Maximum $string.Length)]
        }
    
    $newString
    • #90728

      Alexander Holmeset
      Participant

      Awesome, thanks!

    • #90731

      Jeremy Corbello
      Participant

      Should probably have explained what I did, sorry about that.

      A string, such as $string in the above code, is simply an array of characters. To navigate an array, you choose the index that you want to move to. Such as the following:

      $string = "asdfadfnglkaslkngalkfnk2342419!1342@sadfadsfad?123412341adfafa"
      $string[0]
          a
      $string[12]
          s

      where 0 and 12 are indexes in the array.
      So what I did was used the Get-Random cmdlet and limited the results to between 0 and the length of the string. Get-Random returns and int value and that is used to navigate the character array.

    • #90733

      Alexander Holmeset
      Participant

      Ah, thanks for explaining. Now i learned something new 🙂

  • #90799

    random commandline
    Participant

    Different Method

    $string = "asdfadfnglkaslkngalkfnk2342419!1342@sadfadsfad?123412341adfafa"
    $array = $string -split '' | Where-Object {$_ -ne ''}
    Get-Random -InputObject $array -Count 10
    

You must be logged in to reply to this topic.