My first productionised powershell script

I’ve been tooling around with powershell recently, trying to teach myself some basics, and a recent support request which would have previously been done manually looked like a perfect opportunity for a little ps1 script.

The request was to disable a feature on the website which is configured from a setting in the web.config file on each server. Since web.configs are xml files, I thought I could treat it as such, traversing and editing values as needed.

So here it is; pretty lengthy for what it’s doing since I don’t know the nicer ways of doing some things (e.g., var foo = (bar == baz ? 0 : 1), and var sna = !sna), and as such any comments to help out would be appreciated:

function ValueToText([string] $val){	
	if ($val -eq "1"){return "enabled"}
	else {return "disabled"}

[System.Xml.XmlDocument] $xd = new-object System.Xml.XmlDocument
# pipe-delimited servers to work against
$servers = "||" 

foreach ($server in $servers.Split("|")) {
	write-host "Now configuring " $server
	$file = "\\" + $server + "\d$\Web\web.config"	

	# save a backup, just in case I snafu the site
	$$file + ".bak") 

	# keys to edit
	$nodelist = $xd.selectnodes("/configuration/appSettings/add[contains(@key,'Chat')]") 

	foreach ($node in $nodelist) {
	  $key = $node.getAttribute("key")
	  $val = $node.getAttribute("value")
	  $setting = ValueToText($val)
	  $prompt = $key + " is currently " + $setting + ": toggle this? Y/N"
	  $toggle = read-host $prompt
	  if ($toggle -eq "Y" -or $toggle -eq "y"){
		if ($val -eq "1") {$newbool = "0"}
		else {$newbool = "1"}
		$node.setAttribute("value", $newbool)
		$newsetting = ValueToText($newbool)
		$prompt = $key + " is now " + $newsetting
		write-host $prompt
write-host * done *

It’s probably not much more than a “hello world”, but it certainly helped me out recently 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *