Powershell根据给定的计数选择一个随机字母并将每个字母动态分配给一个唯一的变量?

Powershell to choose a random letters based on the given count and dynamically assign each to a unique variable?

如何使用 Powershell 根据给定的计数选择一个随机字母并将每个字母动态分配给一个唯一变量?

我有以下代码,但我不确定如何执行上述操作,请问有什么想法吗?

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

我希望每个字母的输出存储在 3 个不同的变量中,例如 Ar1、Ar2 和 Ar3(如果 $Count = n,则以此类推 Arn)


如果你真的需要不同的变量($Ar1, $Ar2, ... $Ar<n>),这里是最简洁的解决方案:

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

注意:([char[]] (([char] 'a')..([char] 'n'))) 是缩写
'a','b','c','d','e','f','g','h','i','j', 'k', 'l', 'm','n'.

在 PowerShell Core 中,您可以简单地使用 ('a'..'n').

还要注意 -Name 参数 - 要创建的变量的名称 - 是如何通过脚本块动态计算的。
在脚本块的这种所谓的延迟绑定用法中,它在子变量范围内运行,因此需要使用 [ref] 实例来引用调用方范围内的序列号 $iref
相比之下,您传递给 ForEach-ObjectWhere-Object cmdlet 的脚本块直接在调用者的范围内运行。
此 GitHub 问题中讨论了这种令人惊讶的差异。


试试这样的

1
2
3
4
5
6
7
8
9
10
11
$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
}


我是新来的,但我设法创建了一个脚本,该脚本从字符列表中返回一个随机字符,如果要返回多个字符,您还可以从中选择更多值。 powershell 的 Get-Random 内置函数使它变得更容易

1
2
3
$select = 1
$Mood = Get-Random -InputObject 'b', 'd','g','p','s','y' -Count $select
Write-Output $Mood

首先,我同意 Lee_Dailey 的观点,即创建这样的变量不是一个好主意..

但是,它可以这样做:

1
2
3
4
5
6
7
8
$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.

要查看创建的内容,您可以使用 Get-Variable 'Ar*' 将显示如下内容:

1
2
3
4
5
6
Name                           Value
----                           -----
Ar1                            m
Ar2                            d
Ar3                            j
args                           {}