首页 > 解决方案 > Loop through function until unique value

问题描述

I made a powershell script to do some stuff with csv files. I have a problem with my second import. The script is divided in few section, like this :

Firt part ---- Classic variables declaration
Second part ---- Loop through my first csv
Third part ---- Function to loop through ma second csv
Last part ---- Actions with 3 last sections

My function in the third part look like this :

Function FindRef {
param (
    [Parameter(Mandatory)]
    $Name
)
$RefList = Import-Csv "PATHTOMYCSV\ref.csv" -Delimiter ';'

foreach ($Ref in $RefList) {
     if ($Ref.Company -eq $Name -or $Ref.Model -eq $Name) {          
        Write-Host "$($Ref.Company), $($Ref.Model) and reference is $($Ref.Reference)"
        $PhoneRef =  $Ref.reference 
    }
}

}

When I call y function "FindRef" with "Samsung" parameter for example it return me :

Samsung Galaxy A21s REF
Samsung Galaxy J2 Core REF
Samsung Galaxy A Quantum REF
Samsung Galaxy A71 REF
Samsung Galaxy A51 REF 
Samsung Galaxy A21 REF 
Samsung Galaxy Tab S6 Lite REF
Samsung Galaxy M11 REF 
Samsung Galaxy A31 REF
Samsung Galaxy A41 REF 
Samsung Galaxy M21 REF 
Samsung Galaxy A11 REF 
Samsung Galaxy M31 REF 
Samsung Galaxy S20 Ultra 5G REF 
Samsung Galaxy S20 Ultra REF
Samsung Galaxy S20+ REF
Samsung Galaxy Z Flip REF 
Samsung Galaxy Tab S6 REF 

In the example above with the name "Samsung", I have too many results, I need only one reference.

I would like to loop on this function as long as it returns several results, until I have a unique reference.

I don't see how to do this, do you have any ideas?

PS : The result of my function when I call it :

RefFunction powershell

My csv :

Ref.csv
Regards,

标签: powershell

解决方案


我终于找到了解决我的问题的方法,我与你分享。我痴迷于我的功能,这显然没有必要!

$PhoneRef = ""
$RefList = Import-Csv "C:\Users\SRV-VDG\Desktop\Scripy\Ref.csv" -Delimiter ';'
$I=0
while ($I -ne 1) {
    $Name = Read-host -Prompt 'Input the name '
    $I=0
    foreach ($Ref in $RefList) {
        if ($Ref.Company -eq $Name -or $Ref.Model -eq $Name) {          
            Write-Host "$($Ref.Company), $($Ref.Model) and reference is $($Ref.Reference)"
            $PhoneRef =  $Ref.Reference 
            $I++
        }
    }
}

推荐阅读