none
Convert string into array? RRS feed

  • Question

  • Hi,

    I'm trying to convert a string into an array but fail.

    This is the string

    $users = 'user01
    user02'

    Tried different things, but guess I need to do it like this ...(?)

    $separator = ","
    $array = @()
    $array = [string]::Join($separator,$users)

    What am I missing here

    Please advise.

    J.


    Jan Hoedt

    Friday, September 22, 2017 9:37 AM

Answers

  • I think it is a language issue with Jan.  He may have "join" and "split" mixed up.

    To split a string on boundaries it is easiest to use a RegEx:

    $users = 'user01
    user02
    user03,user04'
    $users -split '\s|,'
    #or
    $users -split '\W'

    This can be generalized to extract all words into an array.


    \_(ツ)_/


    • Edited by jrv Friday, September 22, 2017 10:13 AM
    • Marked as answer by janhoedt Monday, October 30, 2017 5:22 PM
    Friday, September 22, 2017 10:12 AM

All replies

  • "$users" is a string.  "Join" requires an array. an array of strings is delimited by a comma and not a line break.


    \_(ツ)_/

    Friday, September 22, 2017 9:42 AM
  • Hi Jan,

    you just call split:

    $users = 'user01
    user02'
    $Users.Split("`n")

    The trick is knowing what the linebreak character ("`n") is :)

    Cheers,
    Fred


    There's no place like 127.0.0.1

    Friday, September 22, 2017 9:43 AM
  • But he wants to join the string.  Why convert it to an array then join it when you can just remove the line break.  If the exercise is to join strings than crate a comma separated array of strings:

    $users = 'user1','user2'

    That is an array and it can be joined.


    \_(ツ)_/

    Friday, September 22, 2017 9:46 AM
  • Well, his original question was this:

    I'm trying to convert a string into an array but fail.

    So I was showing him how to split strings into arrays of strings. If it's all about how to define an array in a script, your examples is the obvious way to go.


    There's no place like 127.0.0.1

    Friday, September 22, 2017 10:04 AM
  • I think it is a language issue with Jan.  He may have "join" and "split" mixed up.

    To split a string on boundaries it is easiest to use a RegEx:

    $users = 'user01
    user02
    user03,user04'
    $users -split '\s|,'
    #or
    $users -split '\W'

    This can be generalized to extract all words into an array.


    \_(ツ)_/


    • Edited by jrv Friday, September 22, 2017 10:13 AM
    • Marked as answer by janhoedt Monday, October 30, 2017 5:22 PM
    Friday, September 22, 2017 10:12 AM