Home > OS >  how to make unique entry in array in hashtabe
how to make unique entry in array in hashtabe

Time:03-31

I have following line in test1.txt

bpdppa301p.corpads.local 86929680 JC_UNIX_FS01_INCR JC_FS UNIX_FS01_INCR incr 02/24/2022 03/30/2022 03/30/2022  disk 1645678800 backup 84 MB /dbwsrp01/dbwsrp01           JCBDD1300P.corpads.local
bpdppa302p.corpads.local 82578060 MN_DB_ORA                manual 02/24/2022 04/21/2022 03/31/2022         disk 1645678854              80 MB RMAN:PFDPRE01_jf0mjj9l_1_1    MNBDD3302P.corpads.local
bpdppa301p.corpads.local 86929880 JC_UNIX_FS01_INCR JC_FS UNIX_FS01_INCR incr 02/24/2022 03/30/2022 03/30/2022  disk 1645678800 backup 84 MB /dbwsrp01/dbwsrp01           JCBDD1300P.corpads.local

I like to grab unique names after number but before word (incr or manual ). so i used below code.

$backupLogLines = @(Get-Content C:\scripts\test1.txt) -match "incr|full|manual"
$planTable = @{}

foreach ($line in $backupLogLines)
{
    $metadataParts = $line -csplit "incr|full|manual"

    # first string is host name, 
    # second string is discarded, 
    # ... and the rest are backup plans
    $clientHostName,$null,$backupPlans = -split $metadataParts[0]    

    if(-not $planTable.Contains($clientHostName)){
        # Create new array containing the backup plans for the current
        $planTable[$clientHostName] = @($backupPlans)
    }
    else {
        $planTable[$clientHostName]  = $backupPlans
    }
}

but $backupPlans may have duplicates too. how can avoid so hashTable has only unique plans ??

CodePudding user response:

You can rewrite the existing code to use nested hashtables, like this:

$backupLogLines = @(Get-Content C:\scripts\test1.txt) -match "incr|full|manual"
$planTable = @{}

foreach ($line in $backupLogLines)
{
    $metadataParts = $line -csplit "incr|full|manual"

    # first string is host name, 
    # second string is discarded, 
    # ... and the rest are backup plans
    $clientHostName,$null,$backupPlans = -split $metadataParts[0]    

    if(-not $planTable.Contains($clientHostName)){
        # Create new inner hashtable to hold observed backup plans
        $planTable[$clientHostName] = @{}
    }

    foreach($plan in $backupPlans){
        $planTable[$clientHostName][$plan] = $true
    }
}

If the same $plan is observed multiple times for the same client, the script will now simply update/set the same table entry that already exists.

To convert the inner values to arrays at the end:

foreach($key in @($planTable.PSBase.Keys)){
    $planTable[$key] = @($planTable[$key].PSBase.Keys)
}
  • Related