Config file for Powershell script in SharePoint 2010

Config file for Powershell script in SharePoint 2010
4 votes, 4.00 avg. rating (82% score)

Introduction

In this article we will see how we can set a config file for a powershell script. While running script file, rather than setting the global variable values directly in the script; it’s always advisable and best practice to have a config file.
So, we will only change the config file based on the environment and script will read values from the config file.

Read from Config file

Create a config file which holds the values. For example create AdiSiteConfig.xml file in the same directory where the script file is there

<?xml version="1.0"?>
<Config>
<AdiSiteUrl>www.adicodes.com</AdiSiteUrl>
</Config>


The following script will read the values from the config.

$runningDir = resolve-Path .\
$configXmlPath = join-path -path $runningDir -childpath "AdiSiteConfig.xml"
1$SiteConfig = get-content $configXmlPath
$siteUrl = $SiteConfig.config.AdiSiteUrl
try
{
	write-host $siteUrl
	$web = Get-SPWeb -identity $siteUrl
}
catch
{
write-host $error[0]

}

The above example reads the values from the config file AdiSiteConfig.xml which resides in the same location where script file is there.

If you want to have another location for config file just set the $configXmlPath variable with custom location value
Ex:
$configXmlPath = “C:\Custom\NewAdiSiteConfig.xml”

The code $SiteConfig.config.AdiSiteUrl is the one which gets the AdiSiteUrl node value from the AdiSiteConfig.xml file. config is root node and AdiSiteUrl node is the subnode under root node.

Conclusion

Whenever we are providing a script file, it should be a practice to provide a config file. But, we should try to avoid the practice of changing variables in script file. We should rely mostly on the config file. In this way we can maintain the delivery package very easily.

Let me know if you have any comments and happy coding :)

April 28, 2012 В· Adi В· No Comments
Tags: , , ,  В· Posted in: Packaging and Deployment, Powershell, Sharepoint 2010

Leave a Reply

What is 6 + 10 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)