1

How can I use Powershell to choose a random letter based on the given count and dynamically assign each to a unique variable?

I have this below code, but I am not sure how to go about doing the above, any ideas, please?

$Count =3
$a = Get-Random -InputObject 'a','b','c','d','e','f','g','h','i','j', 'k', 'l', 'm','n' -Count $Count

I expect the output of each letters to be stored in 3 different variables like Ar1, Ar2 and Ar3 ( and so on Arn if the $Count = n)

GhostCat
  • 137,827
  • 25
  • 176
  • 248
Sammy123
  • 83
  • 1
  • 2
  • 6
  • 2
    generally speaking, it is a VERY BAD IDEA to create variables programmatically. you already have the 3 values in an array. the array is easily known - no "what is the name of the $Var that value is in?". [*grin*] if you want to address the values, use the array index - `$A[1]` - to get the 2nd item in the array. – Lee_Dailey Oct 25 '18 at 07:05
  • Welcome to Stack Overflow! Other users marked your question for low quality and need for improvement. I re-worded/formatted your input to make it easier to read/understand. Please review my changes to ensure they reflect your intentions. Feel free to drop me a comment in case you have further questions or feedback for me. – GhostCat Oct 25 '18 at 07:07
  • 1
    But I agree with the above: there is no point in creating variable *names* dynamically. – GhostCat Oct 25 '18 at 07:07
  • 2
    Please take a step back and describe the actual problem you're trying to solve instead of what you perceive as the solution. Why do you think you need individual variables for the selected letters? What problem would using individual variables solve that using the array variable you already have would not? – Ansgar Wiechers Oct 25 '18 at 07:21
  • I am developing a chat bot in python. (I am pretty new to PS, hence seeking help). The Bot will ask for the user requirement to develop a simple Maths program in python (Addition for an instance) on how many numbers the user wants to add. So if the $Count is 3, then three different variables need to be automatically(/randomly) picked and dynamically used inside the python code as "$Arn = Int(input("Enter the number")) #(where 'n' is the $Count user keyed-in). I bet you would either think this whole thing is silly or you will appreciate me ;) . – Sammy123 Oct 25 '18 at 08:01
  • The Python has the API + code built around it to interact with other Apps. And I use Powershell to do some basic operations (locally on my windows laptop) doing this proof of concept of bots developing simple maths based on user input. – Sammy123 Oct 25 '18 at 08:09
  • Here's an answer I wrote earlier about "variable variables" (variables where the name changes), explaining why they are useless (you can't write the variable name in your source code if you don't know what it is), how you can make them if you have to (`New-Variable` cmdlet), and what else you can use, and links to a bunch of related questions .. https://stackoverflow.com/a/40477933/478656 – TessellatingHeckler Oct 25 '18 at 08:29
  • @Sammy123 - please, save yourself a freaking _disaster_ by using an array. ask for `$Count` number of entries, store them in an array, iterate thru the array taking action as appropriate. not knowing the $Var names in advance is _actively seeking to make your code confusing_. use an array - it is what arrays are **_for_**. [*grin*] – Lee_Dailey Oct 25 '18 at 10:22

4 Answers4

1

try Something like this

$Count =3
$a = Get-Random -InputObject 'a','b','c','d','e','f','g','h','i','j', 'k', 'l', 'm','n' -Count $Count

for ($i = 0; $i -lt $a.Count; $i++)
{ 
    #Traitment with element in $i posoition
    $Current=$a[$i]

    #use $Current for your traitment
    $Current
}
Esperento57
  • 16,521
  • 3
  • 39
  • 45
  • Many thanks Esperento57!!. Appreciate it. However I am still looking to refine the code that meets my actual requirement. – Sammy123 Oct 25 '18 at 08:05
1

If you truly need distinct variables ($Ar1, $Ar2, ... $Ar<n>), here's the most concise solution:

$iref = [ref] 1
$Count = 3
Get-Random -InputObject ([char[]] (([char] 'a')..([char] 'n'))) -Count $Count |
  New-Variable -Force -Name { 'Ar' + $iref.Value++ }

Note: ([char[]] (([char] 'a')..([char] 'n'))) is short for
'a','b','c','d','e','f','g','h','i','j', 'k', 'l', 'm','n'.

In PowerShell Core, you could simply use ('a'..'n').

Also note how the -Name argument - the name of the variable to create - is calculated dynamically, via a script block.
In this so-called delay-bind usage of a script block, it runs in a child variable scope, hence the need to use a [ref] instance to refer to the sequence number $iref in the caller's scope.
By contrast, script blocks you pass to the ForEach-Object and Where-Object cmdlets run directly in the caller's scope.
This surprising discrepancy is discussed in this GitHub issue.

mklement0
  • 382,024
  • 64
  • 607
  • 775
0

Firts of all, I agree with Lee_Dailey that creating variables like this is NOT a good idea..

However, it can be done like so:

$Count = 3
$a = Get-Random -InputObject 'a','b','c','d','e','f','g','h','i','j', 'k', 'l', 'm','n' -Count $Count

for ($i = 0; $i -lt $a.Count; $i++) { 
    $varname = "Ar$($i + 1)"
    Remove-Variable $varname -ErrorAction SilentlyContinue
    New-Variable -Name $varname -Value $a[$i]
}

Note that for this to work, you must first remove the possible already existing variable with that name, which can lead to unforeseen problems in the rest of your code.

To see what is created, you can use Get-Variable 'Ar*' which will display something like this:

Name                           Value
----                           -----
Ar1                            m
Ar2                            d
Ar3                            j
args                           {}
Theo
  • 57,719
  • 8
  • 24
  • 41
0

i'm new around here but I manage to create a script that returns a random char from a list of characters, if want to return multiple characters you can also select more values from it. the Get-Random built-in function from powershell makes it a lot easier

$select = 1
$Mood = Get-Random -InputObject 'b', 'd','g','p','s','y' -Count $select
Write-Output $Mood
Iago Barreto
  • 103
  • 1
  • 11