How to concatenate array of integers into comma separated string

前端 未结 4 960
陌清茗
陌清茗 2021-01-22 01:55

I have two question, acually:

  1. How to join array of integers into comma separated string? (1,2,3) => \"1,2,3\"
  2. How to convert array of integers t
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-22 02:42

    In your question, you've commented out the following snippet:

    ($arraylist-join -',')
    

    because it returns the error Cannot convert value "," to type "System.Int32"...

    The reason for this is the dash - in front of ','.

    In PowerShell, only operators and parameters are prefixed with a dash, and since ',' is neither (it's an argument to an operator), the PowerShell parser gets super confused and tries to treat -',' as a value expression that would result in a negative number.

    Just void the dash and you'll be fine:

    $arraylist -join ','
    

    Finally, you can easily cast an array of integers to an array of strings with the unchecked cast operator -as (PowerShell 3.0 and newer):

    $StringArray = 1,2,3,4,5 -as [string[]]
    

    or with an explicit cast (PowerShell 2.0-compatible):

    $StringArray = [string[]]@(1,2,3,4,5)
    

提交回复
热议问题