In Powershell v4, I need to read in the contents of a file that contains SKUs and associated product names (likely comma-delimited), randomize those entries, then display a random number of the resulting SKUs and names. For instance, there may be a file with 12 product names and associated SKUs in it. On the first run, it might result in something like this:
SKU: 123456, ProductName: Apples
SKU: 789012, ProductName: Oranges
...and the next time it's run, it might result in this:
SKU: 524367, ProductName: Bananas
SKU: 235023, ProductName: Avocados
SKU: 123456, ProductName: Apples
SKU: 543782, ProductName: Peaches
...and so on. The number of entries in the list of SKUs and products could be as large as twenty thousand, but I'd only need to display between one and fifty SKUs and products at a time. Is there a way to accomplish this within Powershell?
I'm new to Powershell, but I have the basics down; thus far, I have mostly just done a lot of Get-WMIObject commands or interacting with processes and services. Forgive my wordiness with the remarks below; I'm trying to make my goal and process as plain as possible.
# 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]
I would put the SKUs and product names in a CSV:
You can get a random subset of 1 to 50 elements from a CSV like this (as suggested by @MikeShepard):
If you also want to be able to access the product list by SKU you could read the CSV into a hashtable and modify the above code like this: