Purpose of [Char[]] in PowerShell

powershell, powershell-3.0

Solution

PowerShell by default does type casting on the fly, as operations call them.

$MyAnswer = 4 + 4
Write-Host $MyAnswer

Will see the operation 4+4 and store them as an integer value of 8. In the above script it will write the integer 8.

PowerShell is also flexible for strict typecasting where you can explicitly use a datatype

$MyAnswer = [string]4 + 4
Write-Host $MyAnswer

and

$MyAnswer = "4" + "4"
Write-Host $MyAnswer

Both of these will see the two 4's as a string, and write out "44"

As for what the script above is doing, it is creating a character array of "_ " characters for each letter (char) in the $targetWord variable.

If you run it from the console, and do

write-host $targetWord write-host $wordProgress

You get (in my case)

 America
 _ _ _ _ _ _ _

The [char[]] is simply an explicit declaration of a character array to over ride any odd default PowerShell behavior.

Problem

What is the basic purpose of [char[]] in PowerShell. Is it parsing to char array ? For example : ``` $random = Get-Random -Minimum 0 -Maximum 5; $names="America","Iran","Poland","Cat","PowerShell"; $targetWord = $names[$random]; [Char[]]$wordProgress = "_" * $targetWord.Length ```

Original source