Reputation: 3
I'm trying to write a script to extract 2 variables 'code' and 'description' and write them into this template.
<CodeDescriptions>
<CodeDescription>
<Code>*code*</Code>
<Description>*description*</Description>
</CodeDescription>
</CodeDescriptions>
For every set of variables it finds it writes the template and inserts the variables.
my CSV file looks like this
code,description
0001,first
0002,second
0003,third
My code so far:
$DB = Import-Csv $PSScriptRoot\Variables.csv
Set-Content $PSScriptRoot\file.txt
foreach ($Entry in $DB) {
$First = $Entry.First
$Second = $Entry.Second
# Echo values to verify result (test purposes only)
Write-Host $First
Write-Host $Second
# Write template to file
$var=
"<CodeDescriptions>
<CodeDescription>
<Code>*code*</Code>
<Description>*description*</Description>
</CodeDescription>
</CodeDescriptions>"
Add-Content $PSScriptRoot\file.txt $var
# replace inserts with correct variables
}
As I said i'm still getting familiar with the code my goal is to extract 2 variables from 1 line at a time. Then write the template to a file with the correct variables and loop that until all variables are entered.
The finished product would look like this
<CodeDescriptions>
<CodeDescription>
<Code>0001</Code>
<Description>first</Description>
</CodeDescription>
</CodeDescriptions>
<CodeDescriptions>
<CodeDescription>
<Code>0002</Code>
<Description>second</Description>
</CodeDescription>
</CodeDescriptions>
<CodeDescriptions>
<CodeDescription>
<Code>0003</Code>
<Description>third</Description>
</CodeDescription>
</CodeDescriptions>
Upvotes: 0
Views: 77
Reputation: 15824
You have two problems.
First of all, Import-Csv defines the names of the properties based on the headers in the first row, so your foreach loop which starts like this:
foreach ($Entry in $DB) {
$First = $Entry.First
$Second = $Entry.Second
Should start like this:
foreach ($Entry in $DB) {
$Code = $Entry.Code
$Description = $Entry.Description
Then you need to replace *code*
with $Code
and *description*
with $Description
in your $var
(or skip the intermediary variable and just write:
Add-Content $PSScriptRoot\file.txt @"
<CodeDescriptions>
<CodeDescription>
<Code>$Code</Code>
<Description>$Description</Description>
</CodeDescription>
</CodeDescriptions>
"@
Upvotes: 2