从随机数组中检索随机数量的项目

迈克尔·H

在Powershell v4中,我需要读入一个包含SKU和相关产品名称(可能用逗号分隔)的文件的内容,将这些条目随机化,然后显示生成的SKU和名称的随机数。例如,可能有一个包含12个产品名称和相关SKU的文件。在第一次运行时,可能会导致如下所示:

SKU: 123456, ProductName: Apples
SKU: 789012, ProductName: Oranges

...并且下次运行时,可能会导致以下结果:

SKU: 524367, ProductName: Bananas
SKU: 235023, ProductName: Avocados
SKU: 123456, ProductName: Apples
SKU: 543782, ProductName: Peaches

...等等。SKU和产品列表中的条目数可能多达两万,但我一次只需要显示一到五十个SKU和产品。有没有办法在Powershell中完成此任务?

我是Powershell的新手,但是我掌握了一些基础知识。到目前为止,我几乎只是完成了许多Get-WMIObject命令或与流程和服务进行交互。请原谅我的话。我试图使我的目标和过程尽可能简单。

# Create the arrays of SKUs and Product names (I currently have them in two separate files,
# but can combine them easily - I separated them during my experimentation with this
# problem).
$SKU_Array = Get-Content $ScriptFolder\SKUs.txt
$Product_Array = Get-Content $ScriptFolder\Product_Names.txt

# There are 12 items in the sample files, but .Length doesn't count zero, so we subtract
# one index number from the array so that we don't end up calling on an empty item.
$NumberOfSKUs = $SKU_Array.Length - 1
$NumberOfProductNames = $Product_Array.Length - 1

# Pick a random item from the array using the whole range of index numbers (I stopped
# worrying about the SKUs, and was just concentrating on getting the product names
# portion working here).
$RandomProductName = 0..$NumberOfProductNames | Get-Random

# Display the item picked in the previous line; thus far, I haven't figured out how to
# accomplish the rest of my goal.
$Product_Array[$RandomProductName]
安斯加·威彻斯(Ansgar Wiechers)

我会将SKU和产品名称放入CSV:

SKU,ProductName
524367,Bananas
235023,Avocados
123456,Apples
543782,Peaches
789012,Oranges

您可以从CSV这样的CSV中获取1到50个元素的随机子集(如@MikeShepard所建议):

$products = Import-Csv 'C:\path\to\products.csv'

$num = (Get-Random -Minimum 0 -Maximum 50) + 1

$products | Get-Random -Count $num

如果您还希望能够通过SKU访问产品列表,则可以将CSV读取到哈希表中,然后修改上述代码,如下所示:

$products = @{}
Import-Csv 'C:\path\to\products.csv' | % {
  $products[$_.SKU] = $_.ProductName
}

$num = (Get-Random -Minimum 0 -Maximum 50) + 1

$products.Keys | Get-Random -Count $num | % { $products[$_] }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章