Get-random characters from one long word/string?

Welcome Forums General PowerShell Q&A Get-random characters from one long word/string?

This topic contains 5 replies, has 3 voices, and was last updated by

 
Participant
11 months, 2 weeks ago.

  • Author
    Posts
  • #90721

    Participant
    Points: 0
    Rank: Member

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

  • #90722

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

      Participant
      Points: 0
      Rank: Member

      Awesome, thanks!

    • #90731

      Participant
      Points: 22
      Rank: Member

      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

      Participant
      Points: 0
      Rank: Member

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

  • #90799

    Participant
    Points: 10
    Rank: Member

    Different Method

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

The topic ‘Get-random characters from one long word/string?’ is closed to new replies.