1

I am trying to take the output of my foreach loop and apply the array to a string that reads on one line. Here is my code so far:

$upper = 65..90
$lower = 97..122
foreach ($i in $upper)
{
[char]$i 
}
foreach ($i in $lower)
{
[char]$i
}

I'm guessing I need to convert the output of the scriptblock to a variable and use the -join option, but everywhere I look I'm struggling to find how to structure that. Any guidance would be appreciated.

1 Answer 1

1

For this particular case, ForEach(type convertToType) is very useful, here is a cool way to get your lower and upper case dictionary string:

$lowerDict = [string]::new(([int][char]'a'..[int][char]'z').ForEach([char]))
$upperDict = $lowerDict.ToUpper()

If you have access to PowerShell Core, it can be reduced to:

$lowerDict = [string]::new('a'..'z')
$upperDict = $lowerDict.ToUpper()

As for what you are struggling on, how to do it with what you currently have (a foreach loop). You can capture all the output from the loop first:

$upper = foreach ($i in 65..90) { [char]$i }

Now, $upper is an array of chars, then to convert it to string, you can either use -join (guessed right) or [string]::new(...) as I did on my previous example:

$upperDict = -join $upper
# OR
$upperDict = [string]::new($upper)
Sign up to request clarification or add additional context in comments.

2 Comments

That makes sense. I ended up using the [string]::new method and it's working as intended. I appreciate the help!
@SamR.F. happy to help! please, consider accepting the answer if it was helpful

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.