Powershell loop with numbers to alphabet

18.9k views Asked by At

I need help with the following: Create a for loop based on the conditions that the index is initialized to 0, $test is less than 26, and the index is incremented by 1 For each iteration, print the current letter of the alphabet. Start at the letter A. Thus, for each iteration, a single letter is printed on a separate line. I am not able to increment the char each time the loop runs

for ($test = 0; $test -lt 26; $test++)
{
[char]65
}

I have tried multiple attempts with trying to increment the char 65 through 90 with no success. Is there an easier way to increment the alphabet to show a letter for each loop that is ran?

4

There are 4 answers

1
Cassio Farias Machado On BEST ANSWER

You can sum your loop index with 65. So, it'll be: 0 + 65 = A, 1 + 65 = B ...

for ($test = 0; $test -lt 26; $test++)
{
    [char](65 + $test)
}
0
Daniel Ferreira On

PS2 to PS5:

97..(97+25) | % { [char]$_ }

Faster:

(97..(97+25)).ForEach({ [char]$_ })

PS6+:

'a'..'z' | % { $_ }

Faster:

('a'..'z').ForEach({ $_ })
0
KoZm0kNoT On

The following example does not assume 'A' is 65 and also allows you to change it to whatever starting drive you desire. For example, to start with 'C' and go to 'Z':

$start = 'C'
for ($next = 0; $next -lt (26 + [byte][char]'A' - [byte][char]$start); $next++) {
    [char]([byte][char]$start + $next)
}
0
KERR On

Here's a way to find the first available drive. It checks drives E to Z, and stops on the first available one:

101..(97+25) | % { if(!( get-psdrive ([char]$_ ) -ea 0 ) ) {$freedrive = ([char]$_ ); break} }
$freedrive