Nirav Patel
Nirav Patel

Reputation: 75

Powershell How to get only unique result instead of all

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

Upvotes: 0

Views: 66

Answers (1)

Olaf
Olaf

Reputation: 5232

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 
}

Upvotes: 1

Related Questions