Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Variable names with random numbers

I want to declare variables with random numbers in the name, such as

$var123 = "A"
$var456 = "B"
$var789 = "C"

by using Get-Random for the number part.

What have I to write behind $var if $rnd = Get-Random? Or is there another way to declare such variables?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Update: The real use case is that I have trouble with Add-Type and hoped I could solve it with this workaround. But it still does not work as expected. It works for the very first time, but after changing the C# code, it still shows the old code.

Any suggestions? I am running PowerShell 7.2.1 on a Mac computer.

$rnd = Get-Random
$code =
@"
    using System;
    namespace HelloWorld {
        public class Program {
            public static int Main() {
                #return 123; # first try, working well
                return 456; # after changing, still returns 123
            }
        }
    }
"@

New-Variable -Name "var$rnd" -value $code
Add-Type -TypeDefinition (Get-Variable -Name "var$rnd" -ValueOnly) -Language CSharp 
Write-Host (Invoke-Expression "[HelloWorld.Program]::Main()")

>Solution :

You would need to use New-Variable or Set-Variable if you want to dynamically create them with random names:

'A', 'B', 'C' | ForEach-Object {
    do {
        $varname = "var$(Get-Random -Minimum 100 -Maximum 1000)"
    } until($varname -notin (Get-Variable var*).Name)
    New-Variable -Name $varname -Value $_
}

Get-Variable var*

Worth noting that, using above method will make an infinite loop if you create 901 variables with it. -Minimum and -Maximum should be tweaked if more variables are needed.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading