Home > Mobile >  PowerShell updating a csv file based from a csv file as a source
PowerShell updating a csv file based from a csv file as a source

Time:09-17

I am new to PowerShell or any scripting stuff.

I have here a DataResources(CSV File) which contains of bunch of data's that needs to be inserted into a Results.CSV

Here is my DataResources

enter image description here

For my Result.csv looks like this.

enter image description here

My goal is to export a NEW csv file based from a results.csv as a template and if a HostName/Host match the data contains a value equivalent to UA and PWD will be inserted/updated from ExportResources CSV file to Exported new CSV File

after executing scripts that I have created it only modifies 1 row not all.

enter image description here

This is what I've done so far.

    $DataSource = Import-Csv -Path D:\coding\Powershell\csv\Resources\ExportResources.csv
$DataResults = Import-Csv -Path D:\coding\Powershell\csv\Result\results.csv


foreach ($ItemDataResults in $DataResults) 
{
    $HostName = $ItemDataResults.HostName
    $UA = $ItemDataResults.UA
    $PASSWD = $ItemDataResults.PWD

}

$ItemDataSource = $DataSource | ? {$_.Host -eq $HostName}
if ($UA -eq "" -and $PASSWD -eq "")
{
    $ItemDataResults.UA = $ItemDataSource.UA
    $ItemDataResults.PWD = $ItemDataSource.Passwd

} 



$DataResults | Export-Csv D:\coding\Powershell\csv\new.csv -NoTypeInformation

The result almost meet my expectation but the problem here that it only fills one hostname the rest are empty.

CodePudding user response:

The issue with your script is that you loop through $DataResults once, but you have to iterate through it once for each item in $DataSource if you use the method that you're employing. I believe that a better method is to create a hashtable from one CSV, using the host name as the key, and the whole object as the value, then loop through the second array updating the value for each host. That would look something like this:

$DataSource = Import-Csv -Path D:\coding\Powershell\csv\Resources\ExportResources.csv
$DataResults = Import-Csv -Path D:\coding\Powershell\csv\Result\results.csv

$DataHT = @{}
$DataResults | ForEach-Object { $DataHT.Add($_.HostName,$_) }

ForEach( $Record in $DataSource ){
    $DataHT[$Record.Host].UA = $Record.UA
    $ItemDataResults.PWD = $Record.Passwd
} 



$DataHT.Values | Export-Csv D:\coding\Powershell\csv\new.csv -NoTypeInformation
  • Related