0

I'm trying to get all ASCII numbers and letters from Powershell for use as a key later on.

My code so far looks like this:

[char[]] $keyArray = @()
for($i = 65;$i -le 122;$i++) 
{
    if($i -lt 91 -or $i -gt 96)  
    {
        $keyArray += [char]$i
    }  
}
for($i = 0; $i -le 9; $i++)
{
    $keyArray += ("$i")
}

Write-Host [string]$keyArray

However, when I write this out (last line), I get the following with spaces in between each character:

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9

How can I remove those spaces?

Booga Roo
  • 1,665
  • 1
  • 21
  • 30
Piers Karsenbarg
  • 3,105
  • 5
  • 31
  • 67
  • 1
    `-join(@('A'[0]..'Z'[0];'a'[0]..'z'[0];'0'[0]..'9'[0])|%{[char]$_})` But really use `StringBuilder` instead of that `[char[]] $keyArray = @()`. I does not really want to think about what happens when you then do `$keyArray += ...`. – user4003407 Dec 30 '15 at 11:12
  • Wow. Now I feel stupid. Much simpler thank you. Do you want to add that as an answer so I can accept it. – Piers Karsenbarg Dec 30 '15 at 11:15

3 Answers3

3

You can use -join operator to join array elements. Binary form of that operator allows you to specify custom separator:

-join $keyArray
$keyArray -join $separator

If you really have array of characters, then you can just call String constructor:

New-Object String (,$keyArray)
[String]::new($keyArray) #PS v5

And does not use array addition. It slow and unnecessary. Array operator @() is powerful enough in most cases:

$keyArray = [char[]] @(
    for($i = 65;$i -le 122;$i++)
    {
        if($i -lt 91 -or $i -gt 96)
        {
            $i
        }
    }
    for($i = 0; $i -le 9; $i++)
    {
        "$i"
    }
)

With use of PowerShell range operator you code can be simplified:

$keyArray = [char[]] @(
    'A'[0]..'Z'[0]
    'a'[0]..'z'[0]
    '0'[0]..'9'[0]
)
user4003407
  • 21,204
  • 4
  • 50
  • 60
2

Use the builtin Output Field Seperator as follows (one-line, use semi-colon to separate, and you MUST cast $keyArray to [string] for this to work):

$OFS = '';[string]$keyArray

Reference

sodawillow
  • 12,497
  • 4
  • 34
  • 44
Davemundo
  • 849
  • 9
  • 14
2

If you want one character per line:

Write-Host ($keyArray | out-string)

If you want all chars on one line:

Write-Host ($keyArray -join '')
JohnLBevan
  • 22,735
  • 13
  • 96
  • 178
  • 1
    I was doing like this : $array=New-Object System.Collections.Generic.List[System.Object] for ($i=0; $i -le 6; $i++) { if ($args[$i]) { $array.add("`t"+$args[$i]) } else { $array.add("`t"+0) } } But it was adding a space before the tab. and I added below as you answered : $array=$array -join '' That did work !!!!! Thank you ! – Smug Sep 26 '18 at 00:45