Powershell loop with numbers to alphabet
Asked Answered
M

4

7

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?

Mai answered 8/9, 2017 at 5:37 Comment(3)
0=A 1=B 2=C 3=D ....25=ZMai
0..25 | %{ [char] ($_ + [byte][char] 'A') }Comedic
if all you want it the range of uppercase letters, this will do it ... [char[]]('A'[0]..'Z'[0]). [grin]Bolin
S
17

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)
}
Subclass answered 8/9, 2017 at 5:53 Comment(1)
for ($test = 0; $test -lt 26; $test++) { $char = [char](65 +$test) Write-Host $char } Your suggestion worked out great. Thank youMai
A
7

PS2 to PS5:

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

Faster:

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

PS6+:

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

Faster:

('a'..'z').ForEach({ $_ })
Avenue answered 11/11, 2018 at 14:56 Comment(0)
G
2

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
Gabrielgabriela answered 20/6, 2022 at 3:20 Comment(0)
S
0

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)
}
Softball answered 23/2, 2021 at 17:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.