Using an XML file to store and retrieve settings

If you are unfamiliar with XML then I’d suggest a quick visit to this URL should cover everything you need to know before reading the example below.

https://www.w3schools.com/xml/xml_dtd_intro.asp

You can use an XML file to store and retrieve information and as long as you know the structure you can easily locate and access the information like this: <xmlDocument>.<element>.<element>.setting – a code example should show you how to do this. You can even use where clauses etc. to extract multiple xml elements although I didn’t include any of these in my example- it’s pretty cool and I’ll try and write a few articles on using XML in your PowerShell scripts including storing password securely and creating them from within a script.

The example below has an element with an attribute and this is accessible too using the same methodology but I’d try not to use attributes in an XML doc if I were you – see the recommendation in this link.

https://www.w3schools.com/xml/xml_dtd_el_vs_attr.asp

<?xml version="1.0"?> 
 <Settings> 
  <EmailSettings available="TRUE"> 
   <SMTPServer>smtp.clan8.com</SMTPServer> 
   <SMTPPort>25</SMTPPort> 
   <MailFrom>svc-messagingtasks@man.com</MailFrom> 
   <MailTo>Jason.Bourne@clan8.com</MailTo> 
   <MailTo>James.Bond@clan8.com</MailTo> 
   <MailTo>Joe.Bloggs@clan8.com</MailTo> 
   <MailTo>Jane.Doe@clan8.com</MailTo> 
  </EmailSettings> 
 <Exclusions> 
  <DBName></DBName> 
  <DBName></DBName> 
 </Exclusions> 
 <OtherSettings> 
  <ThresholdMonday>48</ThresholdMonday> 
  <ThresholdOther>24</ThresholdOther> 
 </OtherSettings> 
</Settings>
# Given an example XML file shown above you can reference things 
# in the XML like this: 
[xml]$xmlFile = Get-Content c:\Temp\settings.txt

$smtpServer = $xmlFile.settings.emailsettings.smtpserver
$smtpPort = $xmlFile.settings.emailsettings.SMTPPort
$DistributionList = $xmlFile.settings.emailsettings.MailTo
$attributeValue = $xmlFile.settings.emailsettings.available 
ForEach ( $member in $smtpServer ) {
 write-host "SMTP Server - $member "
}

if ( $smtpPort -is [system.array] ) {
 ForEach ( $member in $smtpPort ) {
  write-host "SMTP Port - $member "
 }
}
else {
 write-host "SMTP Port - $smtpPort"
}

$smtpServer.Gettype()
$DistributionList.GetType()

ForEach ( $member in $DistributionList ) {
 write-host " - $member "
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.