简体   繁体   English

在Powershell中从一个范围生成一个随机数,但排除1

[英]generate a random number in powershell from a range but exclude 1

I want to generate a random number from a range (lets say 1 to 3) but exclude from that range specific number in variable X 我想从一个范围(让我们说1到3)中生成一个随机数,但从该范围中排除变量X中的特定数

So I got this code 所以我得到了这段代码

get-random -inputobject (1..4) | where {$_ -notin $X}

this indeed generate a random number between 1 and 3 but when the generate number is equal to the number in X, it returns nothing. 这确实会生成一个介于1和3之间的随机数,但是当生成的数等于X中的数字时,它什么也不返回。

How can I force it to run again when it happens so I always get a number, don't matter how many tries it takes? 我怎么能迫使它再次发生,所以我总是得到一个数字,不管尝试多少次?

One option is to remove the items you want to exclude before calling Get-Random : 一种选择是在调用Get-Random之前删除要排除的项目:

$InputRange = 1..10
$Exclude = 3,4,5

$RandomRange = $InputRange | Where-Object { $Exclude -notcontains $_ }

Get-Random -InputObject $RandomRange

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM