0

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.

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Hi Thanks, it resolves my problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.