How to write PowerShell code part 1 (Using external xml configuration file)
Posted
by ybbest
on YBBest
See other posts from YBBest
or by ybbest
Published on Sun, 13 May 2012 01:16:39 +0000
Indexed on
2012/05/30
17:03 UTC
Read the original article
Hit count: 592
In this post, I will show you how to use external xml file with PowerShell. The advantage for doing so is that you can avoid other people to open up your PowerShell code to make the configuration changes; instead all they need to do is to change the xml file. I will refactor my site creation script as an example; you can download the script here and refactored code here.
1. As you can see below, I hard code all the variables in the script itself.
$url = "http://ybbest" $WebsiteName = "Ybbest" $WebsiteDesc = "Ybbest test site" $Template = "STS#0" $PrimaryLogin = "contoso\administrator" $PrimaryDisplay = "administrator" $PrimaryEmail = "[email protected]" $MembersGroup = "$WebsiteName Members" $ViewersGroup = "$WebsiteName Viewers"
2. Next, I will show you how to manipulate xml file using PowerShell. You can use the get-content to grab the content of the file.
[xml] $xmlconfigurations=get-content .\SiteCollection.xml
3. Then you can set it to variable (the variable has to be typed [xml] after that you can read the content of the xml content, PowerShell also give you nice IntelliSense by press the Tab key.
[xml] $xmlconfigurations=get-content .\SiteCollection.xml $xmlconfigurations.SiteCollection $xmlconfigurations.SiteCollection.SiteName
4. After refactoring my code, I can set the variables using the xml file as below.
#Set the parameters $siteInformation=$xmlinput.SiteCollection $url = $siteInformation.URL $siteName = $siteInformation.SiteName $siteDesc = $siteInformation.SiteDescription $Template = $siteInformation.SiteTemplate $PrimaryLogin = $siteInformation.PrimaryLogin $PrimaryDisplay = $siteInformation.PrimaryDisplayName $PrimaryEmail = $siteInformation.PrimaryLoginEmail $MembersGroup = "$WebsiteName Members" $ViewersGroup = "$WebsiteName Viewers"
© YBBest or respective owner