0

This is my 1st question. Your help is highly appreciated.

$ser1='E:\1.exe' , 'E:\2.exe'
$sername=("A1Testservice","A1Testservice")

foreach($ser in $sername)
{
    foreach ($ser2 in $ser1)
    {
        New-Service -Name $ser -DisplayName $ser -Description $ser -BinaryPathName $ser2 -ErrorAction SilentlyContinue -StartupType Automatic 
        Restart-Service $ser 
    }
}

Below is the actual result

1.exe A1Testservice,
1.exe A2Testservice

but I need below result
1.exe A1Testservice,
2.exe A2Testservice

zett42
  • 25,437
  • 3
  • 35
  • 72

1 Answers1

1

You have two completely unrelated arrays and use a nested loop to iterate each element of one array over each element of the other array. If I'm assuming right you actually should use a source where you have a relation between the information stored in it. You could use a CSV file for example. Adapted to your example the code could look like this:

$CSV = @'
Name,Binary
'E:\1.exe', 'A1Testservice'
'E:\2.exe', 'A1Testservice'
'@ | ConvertFrom-Csv

foreach ($item in $CSV) {
    New-Service -Name $Item.Name -DisplayName $Item.Name -Description $Item.Name -BinaryPathName $Item.Binary -ErrorAction SilentlyContinue -StartupType Automatic 
    Start-Service $ser 
}
Olaf
  • 4,690
  • 2
  • 15
  • 23
  • Thanks Olaf, it's worked. I appreciated your help. Some small correction: E:\1.exe, A1Testservice E:\2.exe, A2Testservice This value should not in inverted comma(' '). – Nirav Patel Apr 05 '21 at 09:22