简体   繁体   中英

Powershell - .csv split strings

I am trying to use powershell for extracting email addresses from a.csv file. Each row in the.csv may have none or more emails separated by ",".

fe
Email
info@domain.com, email@domain.com, person@contonso.com
something@domain.com

My goal is to write it that way so I can get the "info@ " from the row if it is present + 1 extra email from the row if it is present. If there is no "info@ " get at least 1 or 2 emails from that row.

Here is the fracture of the code, where I am manually able to say on what position is what email, but I am not able to get this part to work in the for cycle which I could use to enumerate the number of occurences as it appears I cannot convert it to int at all.

$Occurrences = $email.Split(",").GetUpperBound(0);
[int]$Occurrences

$data = Import-Csv -path $path
foreach($contact in $data)
{
    $email = $contact.Email

    if($email.Contains("info"))
    {
        $emailSplit = $contact.Email.Split(",")
        $Occurrences = $email.Split(",").GetUpperBound(0);
        [int]$Occurrences
        $name = $domainSplit[0]
        for([int]$i = 0;-lt $Occurrences.ToInt32(); $i++)
        {

        }
    }
}

Any help is appreciated.

This is not a valid CSV Format. Cant you export the data via JSON from the datasource?

You need to split the single lines and then do your operations


$data = Get-Content -path $path
for($i=1; $i -lt $data.Length; $i++)
{
    $emailSplit = [array]$data[$i].Split(",")
    for($j = 0; $j -lt $emailSplit.Length; $j++) {
        <#do your operation here... 
        loop once through the elements, check for info@, and then assign them accoringly...
        #>

    }
}

V2:

$data = Get-Content -path $path
for($i=1; $i -lt $data.Length; $i++)
{
    $emailSplit = [array]$data[$i].Split(",")
    Write-Host ('Results for line: ' + $i)
    $infoFound = $false
    for($j = 0; $j -lt $emailSplit.Length; $j++) {
        if($emailSplit[$j] -match 'Info@*') {
                                            $infoFound = $true
                                            $infoPos = $j
                                            }
    }
    [array]$results = $emailSplit[0]
    $results += $emailSplit[-1]
    if($infoFound) {
        if($infoPos = 0) {$results[1] = $emailSplit[$infoPos]}
        else {$results[0] = $emailSplit[$infoPos]}

    }
    Write-Host ('Element1: ' + $results[0] + ' Element2: ' + $results[1])
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM