pass multiple string value to a single command in loop

Hi I have two file PID and HID which contain list of equal numbers of HIDs and PIDs. I want these HID and PID in file to pass to a command recursively. here’s what i have done.

$PID = get-content pid.txt

$HID = get-content hid.txt

foreach ( ) {

#i want to give each value in pid and hid to following command

handle.exe -c $HID -p $PID


#but it don’t work because i don’t know what condition to give in foreach loop. Please help

I’m new and not a powershell pro but -

Instead of a foreach, I would use a for loop (it is also faster this way). Example below

#Create array one

$a = @("1", "2", "3")

#create array two

$b = @("4", "5", "6")

#starting with the first element of each array (0)

#write the values out to the console

#This will work for any size array because the last

#element of the array is always (count -1) because of 0 based indexing

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


write-host $a[$i] "and" $b[$i]



I should note, this only works if the values you want together are in the same index of the 2 arrays.

I.E. $pid[0] and $hid[0] go together.

Get-Content will generate an array of lines, so the loop needs to get lines based on index. So, something like this should work:

$PID = get-content pid.txt
$HID = get-content hid.txt

for ( $i = 0;$i -le ($PID.Count - 1);$i++ ) {
    "Processing hid {0} and pid {1}" -f $HID[$i],$PID[$i]
    handle.exe -c $HID[$i] -p $PID[$i]

Now, I will say that is a very disjointed method trying to line up content based on index as there are several assumptions. A more Powershell approach is leveraging a PSObject, something like this:

$myobject = @()
$myobject += @{Pid = 123;Hid = 321}
$myobject += @{Pid = 325;Hid = 427}

foreach ($obj in $myobject) {
    "Processing hid {0} and pid {1}" -f $obj.hid,$
    handle.exe -c $obj.hid -p $

Depending on where you get the PID\HID data, it may be easier to do that rather than generate files. There are several folks that have examples:

@crisovan Really close, just one tip, make sure that you subtract 1 from your count if your are referencing an index. Count starts at 1, indexing starts at 0, so if the count was 4 the indexing would end at 3.


If the count of the array is 4 and my for loop uses -lt (not -le) my loop should stop at 3.