I'm trying to convert following xml file into PowerShell dictionary.
<configuration>
<environment id="Test">
<client>ABC</client>
<type>Test</type>
<template> </template>
<targetmachines>
<targetmachine>
<name>Any</name>
<remotedirectory>C:\ServiceDirectory</remotedirectory>
</targetmachine>
</targetmachines>
<connectionStrings>
<DB1>User ID=xx;password=xx=;</DB1>
<DB2>User ID=yy;password=yy=;</DB2>
</connectionStrings>
</environment>
</configuration>
Here is my powershell script:
$environmentId = "Test"
$configxml = [xml] (Get-Content "xmlfile")
$keyValuePairs = New-Object "System.Collections.Generic.Dictionary``2[System.String,System.String]"
$configxml.SelectNodes("descendant::configuration/environment[@id='$($environmentId)']/descendant::text()[normalize-space()]") | Where-Object {$_.Value} |
ForEach-Object {
$keyValuePairs.Add($_.ParentNode.ToString(), $_.Value)
}
Write-Output $keyValuePairs
I'm getting following output:
Key Value
--- -----
client ABC
type Test
name Any
remotedirectory C:\ServiceDirectory
DB1 User ID=xx;password=xx=;
DB2 User ID=yy;password=yy=;
The above PowerShell script is working fine. But i want following output. The difference here is we have extra key called "template" which has empty value. I want to convert empty value elements to dictionary.
Key Value
--- -----
client ABC
type Test
template
name Any
remotedirectory C:\ServiceDirectory
DB1 User ID=xx;password=xx=;
DB2 User ID=yy;password=yy=;
Can someone please suggest me how to update my powershell script. Thanks in Advance.
This should do what you need:
$xml = [xml]'<configuration>
<environment id="Test">
<client>ABC</client>
<type>Test</type>
<template> </template>
<targetmachines>
<targetmachine>
<name>Any</name>
<remotedirectory>C:\ServiceDirectory</remotedirectory>
</targetmachine>
</targetmachines>
<connectionStrings>
<DB1>User ID=xx;password=xx=;</DB1>
<DB2>User ID=yy;password=yy=;</DB2>
</connectionStrings>
</environment>
</configuration>'
$environmentId = "Test"
$dictionary = New-Object 'System.Collections.Generic.Dictionary[string,string]'
$xml.SelectNodes("//configuration/environment[@id='$environmentId']//*[not(*)]") | `
% { $dictionary.Add($_.Name,$_.InnerText) }
Dictionary content
Key Value
--- -----
client ABC
type Test
template
name Any
remotedirectory C:\ServiceDirectory
DB1 User ID=xx;password=xx=;
DB2 User ID=yy;password=yy=;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.