简体   繁体   中英

How can I remove spaces from this PowerShell array?

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:

ABCDEFGHIJKLMNOPQRSTU VWXYZ abcdefghijklmnopqrstu vwxyz 0 1 2 3 4 5 6 7 8 9

How can I remove those spaces?

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]
)

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

If you want one character per line:

Write-Host ($keyArray | out-string)

If you want all chars on one line:

Write-Host ($keyArray -join '')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM