PowerTip: Convert Character Array to String


Summary: Easily convert a character array to a string in Windows PowerShell.

Hey, Scripting Guy! Question How can I use Windows PowerShell to convert data that is returning as an array of characters
          instead of as a single string?

Hey, Scripting Guy! Answer Use the unary operator, and pass the array. In the following example, the first command returns an
          array of characters, and the next the unary operator converts the character array to a single string:

PS C:\> $a = (get-module -l)[0].Path | split-path -Parent

PS C:\> $a[0]

C

PS C:\> $b = (,$a)

PS C:\> $b[0]

C:\Users\ed\Documents\WindowsPowerShell\Modules\ConversionModule

PS C:\>

Comments (6)

  1. David Wyatt says:

    Assuming that you actually had a character array, the simplest way to convert it to a string in PowerShell is to use the unary -join operator:

    [char[]] $charArray = ‘H’, ‘e’, ‘l’, ‘l’, ‘o’
    $string = -join $charArray

  2. Jaap Brasser says:

    [array]$b = $a, or:$b = $a -as [array] Will accomplish the same thing.

  3. jrv says:

    Does not create a character array. It creates an array if strings.

    PS C:scripts> $a = (get-module -l)[0].Path | split-path -Parent
    PS C:scripts> $a.GetType()

    IsPublic IsSerial Name BaseType
    ——– ——– —- ——–
    True True String System.Object

  4. JV says:

    IsPublic IsSerial Name BaseType
    ——– ——– —- ——–
    True True Object[] System.Array

    STILL CANNOT POST WITHOUT BREAK CONVERTING TO

  5. Larry Weiss says:

    Try $a,gettype() and $b.gettype() to see the actual types of the variables. You’ll find that $a is already a string and $b is an array of strings. To start off with a char array use
    [char[]]$a = (get-module -l)[0].Path | split-path -Parent

  6. CodeMaster Bob says:

    @Larry Weiss: True, you now have an array of char but the remainder of the script does not produce a string as desired.

    $b = (,$a) leaves $b as Object[] with a single element of type Char[] (i.e. $a)

    @Jaap Brasser: True, [array]$b=$a and $b=$a -as [array] both accomplish the same thing as $b=(,$a). Thus, all three are incorrect in the context of the question.

    @David Wyatt: The correct next step after the change indicated by Larry Weiss. I would guess that what is happening is that -join first invokes toString() on each element of the Char[] to produce a String[] which is then joined. This is supported by the following:

    PS >> [char[]]$a = "a string of chars".tochararray()
    PS >> $a.tostring()
    System.Char[]
    PS >> $b=(,$a)
    PS >> $b.tostring()
    System.Object[]
    PS >> -join $b
    System.Char[]

    This analysis is provided so that the behaviour (lang="en-gb") of -join can be predicted when supplied with other arrays (e.g. int[] or maybe even datetime[]).

Skip to main content