从多个 XML 中提取数据并生成 CSV 报告 - Powershell

从多个 XML 中提取数据并生成 CSV 报告 - Powershell

我有几个 xml 文件形式的连接字符串。我需要使用所有这些连接字符串生成 CSV 报告,输出如下:

CSV 文件所需的格式

下面是我的 PS 脚本,它对 1 个文件运行良好,并给出了所需的输出。我一直在尝试让它对所有文件都起作用

function extractValues ($string, $values){
    return ($values | %{ $string -match "$_=([^;]+)" | Out-Null; $matches} | %{$_[1]})
}
    [string]$Value1 = '/connectionStrings/add[@name="Value1"]/@connectionString'
    [string]$Value2 = '/connectionStrings/add[@name="Value2"]/@connectionString'
    [string]$Value3 = '/connectionStrings/add[@name="Value3"]/@connectionString'

$files = Get-Childitem –Path C:\inetpub\wwwroot\*\ConfigSections\connectionStrings.config.New.config

foreach ($file in $files) {

[xml]$xml = Get-Content $file


$connectionString = ($xml | Select-Xml -XPath $Value1).ToString()
($serverName, $dbName, $user) = extractValues $connectionString @("Data Source", "Initial Catalog", "User ID")


$connectionString = ($xml | Select-Xml -XPath $Value2).ToString()
($EserverName, $EdbName, $Euser) = extractValues $connectionString @("Data Source", "Initial Catalog", "User ID")

$connectionString = ($xml | Select-Xml -XPath $Value3).ToString()
($SCSserverName, $SCSdbName, $SCSuser) = extractValues $connectionString @("Data Source", "Initial Catalog", "User ID")

$table=@"
Initial Catalog = $Value1,
Value1, connectionstring=Data Source=$serverName, Initial Catalog=$dbName, User ID=$user
Value2, connectionstring=Data Source=$EserverName, Initial Catalog=$EdbName, User ID=$Euser
Value3, connectionstring=Data Source=$SCSserverName, Initial Catalog=$SCSdbName, User ID=$SCSuser
"@


#export to a csv file
$table | Set-Content $home\desktop\test.csv
}

这只会为 1 个连接字符串输出 csv。不确定我遗漏了什么。

谢谢

答案1

感谢@sum1sadmin,我在声明表时遗漏了 +。因此,应该是 $table += 而不是 $table =,因为这个 $table 在 foreach 循环中。

相关内容