2012-09-21 67 views
2

我是PowerShell和脚本/编程的初学者,但我正在尝试编写一个PowerShell脚本,它将搜索目录中的每个XML文档以查找CSV文件第1列中的值并将该找到的值替换为相同CSV中列2中的值。然后该脚本需要转到CSV的下一行并重复该过程并继续,直到CSV的第1列中的所有值都被搜索并相应地被替换。Powershell:搜索用CSV替换XML

我拼凑在一起,但我不知道如何继续下去。

$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 
} 

回答

3

鉴于你的情况,我可能会这样做。

$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 
} 
+0

非常感谢! Chris – user1689028