none
Powershell Sorting or Comparing RRS feed

  • Question

  • I am trying to sort a string list alphabetically.  The user names are in the format of xy-xyz-xyz-test1, xy-xyz-xyz-test2 ....  etc. 

    I am setting the list with a

    $userlist = $userlist + "`n" + $user

    And I am trying to sort the list with the below and it does not work correctly.

    $userlist1 = Sort-Object $userlist.name

    Ultimately I want to compare the usernames of $userlist with those stored in $file with the least amount of code.  I have tried the following:

    1) Compare-Object $file $userlist
    2) if ($file -notcontains $user)

    Neither worked.  I know how I can do it via nested for loops and if statements.  I just want to do it more practically and it doesn't seem to get past the naming scheme of the user names.

    Can anyone help?

    Tuesday, January 21, 2014 5:37 PM

Answers

  • Hi,

    Try creating an array for your userlist:

    $userNames = 'xy-xyz-xyz-test2', 'xy-xyz-xyz-test1'
    $userNames | Sort-Object

    EDIT: Here's an example that uses a foreach loop to add to an array, since that seems pretty close to what you're attempting now:

    $userList = @()
    $userNameList = 'xy-xyz-xyz-test2', 'xy-xyz-xyz-test1', 'xy-xyz-xyz-test3'
    
    foreach ($user in $userNameList) { $userList += $user }
    
    $userList | Sort-Object


    Don't retire TechNet! - (Don't give up yet - 12,575+ strong and growing)


    • Edited by Mike Laughlin Tuesday, January 21, 2014 5:43 PM
    • Marked as answer by Treyb Tuesday, January 21, 2014 6:10 PM
    Tuesday, January 21, 2014 5:41 PM

All replies

  • Hi,

    Try creating an array for your userlist:

    $userNames = 'xy-xyz-xyz-test2', 'xy-xyz-xyz-test1'
    $userNames | Sort-Object

    EDIT: Here's an example that uses a foreach loop to add to an array, since that seems pretty close to what you're attempting now:

    $userList = @()
    $userNameList = 'xy-xyz-xyz-test2', 'xy-xyz-xyz-test1', 'xy-xyz-xyz-test3'
    
    foreach ($user in $userNameList) { $userList += $user }
    
    $userList | Sort-Object


    Don't retire TechNet! - (Don't give up yet - 12,575+ strong and growing)


    • Edited by Mike Laughlin Tuesday, January 21, 2014 5:43 PM
    • Marked as answer by Treyb Tuesday, January 21, 2014 6:10 PM
    Tuesday, January 21, 2014 5:41 PM
  • ya know........  I completely forgot about just creating arrays instead of string lists lol.  It works now ;)
    Tuesday, January 21, 2014 6:11 PM