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

标签 arrays powershell random powershell-4.0

在 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]

最佳答案

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

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

您可以从 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[$_] }

关于arrays - 从随机数组中检索随机数量的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30825025/

相关文章:

powershell - 导出模块变量名称的命名约定

powershell - 使用 Powershell 异步下载多个大文件

c++ - 为什么数字不会保持随机?

c++ - fork进程之间的随机数是相同的

C# 数组[a,b,c] 与数组[a][b][c]?

arrays - 如何在powershell中将string.format与字符串数组一起使用

javascript - 使用map()和/或reduce()来简化Node(或原生JavaScript)中的forEach()语句

c - 如何在 C 中将 2 个 float 组合并到 1 个结构数组中

variables - 如何在 Powershell 中手动增加 $err 计数?

c - glibc rand函数实现