Multiple foreach loops in one Function

Hi folks, new here. Had a quick look at Multiple foreach commands [SOLVED] but I’m still stuck after a few attempts with global variables and functions.

This script will be run by support guys to paste in a;
a) List of usernames
b) List of token serial numbers
c) Have the script combine each line to contain both (with other items - e.g. “action,$user,$serial,item”) for an external program to parse.

…but not sure if it translates.

I can be open about the ask. I work for a company who uses 2FA tokens to log on to resources.
A recent ask is for tokens to be assigned to (non-human) bot users that requires 2FA to log on to a particular application. Human users self-serve so no issue.
The “robot” users need a PIN set and a token serial number assigned to their ID. So there are three “items” in play.

I have taken the list of user (ID) names and ran a “foreach” script to put a random six-digit PIN against each.
This is achieved by parsing a text file with a single line for each, using $variable = Get-Content -Path $path and assigning a random number (can’t remember the command but it works fine). Function:

foreach ($item in$items)
$PINs = Get-Random -Minimum 100000 -Maximum 999999
$output = “stuff,$item,stuff,stuff,$OTHERITEM”

How do I get a “foreach” inside the same Function to ensure the individual variable items are put together in the same output? How do I take a list from (a) user to have $OTHERITEM populate next to $item ?
#That sentence alone sounds awful!

Appreciate the comments.


Sorry, to make more sense, I’d like it to look something like:


Populating the variables from two same-length (possibly different) data sources.

Basically, I’m trying to reduce as much effort on the end user as possible. Maximum = paste numbers in to one file (first variable) then another (second variable).

Hi, welcome to the forum :wave:

If you’ve got the users pasting data, why not just get them to paste it straight into a spreadsheet and save as a CSV file. Then you’ve got ready-made objects with Import-CSV.

If you insist on using single text files, then I would use a for loop rather than a foreach loop. The loop has a counter that indexes the files, pulling the same index position out of each file:

$file1 = Get-Content E:\Temp\File1.txt
$file2 = Get-Content E:\Temp\File2.txt
$file3 = Get-Content E:\Temp\File3.txt

for ($i = 0; $i -lt $file1.count; $i++) {

    Write-Output "$($file1[$i]),$($file2[$i]),$($file3[$i])"

1 Like

Excellent! Thanks Matt.
I’m a bit of a Notepadphile (light and quick) but the CSV idea is good. :slight_smile: