2

I am a beginner at PowerShell and scripting/programming but I am trying to write a PowerShell script that will search through each XML document in a directory for a value found in column 1 of a CSV file and replace that found value with the value in column 2 of the same CSV. The script will then need to go to the next row of the CSV and repeat the process and continue until all values in Column 1 of the CSV have been searched for and replaced accordingly.

I've cobbled the following together but I'm at a loss as to how to proceed.

$c = import-csv C:\somecsv.csv)
$xmls2search=get-childitem C:\somedirectory\*.xml
foreach ($xmldoc in $xmls2search)
{
  (Get-Content $xmldoc.PSPath) | 
  Foreach-Object {$_ -replace $c[i].column1name, $c[i].column2name} | 
  Set-Content $xmldoc.PSPath
}

1 Answer 1

3

Given your situation, I'd probably do something like this.

$c = Import-Csv yourcsv.csv

Get-ChildItem *.xml | Foreach-Object {
  # Out-String in the next line lets you work with a single string rather than an
  # array of strings.
  $xmldoc = (Get-Content $_.PSPath | Out-String)

  # Loop through your CSV, updating $xmldoc with each pass
  $c | Foreach-Object {
    $xmldoc = $xmldoc -replace $_.column1name,$_.column2name
  }

  # Write the updated $xmldoc back to the original XML file's path
  $xmldoc | Set-Content $_.PSPath
}
Sign up to request clarification or add additional context in comments.

Comments

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.