PowerTip: Convert Character Array to String

PowerTip: Convert Character Array to String

  • Comments 6
  • Likes

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:\>

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • 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

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

    STILL CANNOT POST WITHOUT BREAK CONVERTING TO


  • 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

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

  • 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