header image

Using Range operator to generate letters

Posted by: | June 6, 2010 | No Comment |

The range operator is used to generate a sequential set of numbers

1..10 | foreach {$_}

if we try this with letters

PS> a..j | foreach {$_}
The term ‘a..j’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:5
+ a..j <<<<  | foreach {$_}
    + CategoryInfo          : ObjectNotFound: (a..j:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

However we can use the range operator to generate letters like this

## upper case
65..90 | foreach {"$_ $([char]$_)" }

## lower case
97..122 | foreach {"$_ $([char]$_)" }

using the ACSII codes.  if we want to create filea.txt – filej.txt  we can simply do this

97..106 | foreach {New-Item -Path c:\test -Name "file$([char]$_).txt" -ItemType File}

Nice and simple one line of PowerShell.

under: PowerShellV2