1

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?

2
  • 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 += .... Commented Dec 30, 2015 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. Commented Dec 30, 2015 at 11:15

3 Answers 3

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]
)
Sign up to request clarification or add additional context in comments.

Comments

3

If you want one character per line:

Write-Host ($keyArray | out-string)

If you want all chars on one line:

Write-Host ($keyArray -join '')

1 Comment

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 !
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.