<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Solutionizing .NET &#187; PowerShell</title>
	<atom:link href="http://solutionizing.net/category/powershell/feed/" rel="self" type="application/rss+xml" />
	<link>http://solutionizing.net</link>
	<description>Random thoughts on custom development in SharePoint.</description>
	<lastBuildDate>Sat, 12 May 2012 03:45:35 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='solutionizing.net' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Solutionizing .NET &#187; PowerShell</title>
		<link>http://solutionizing.net</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://solutionizing.net/osd.xml" title="Solutionizing .NET" />
	<atom:link rel='hub' href='http://solutionizing.net/?pushpress=hub'/>
		<item>
		<title>Code Review with Git Patches and Outlook via PowerShell</title>
		<link>http://solutionizing.net/2010/12/05/code-review-with-git-patches-and-outlook-via-powershell/</link>
		<comments>http://solutionizing.net/2010/12/05/code-review-with-git-patches-and-outlook-via-powershell/#comments</comments>
		<pubDate>Mon, 06 Dec 2010 02:31:00 +0000</pubDate>
		<dc:creator>Keith Dahlby</dc:creator>
				<category><![CDATA[Git]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[format-patch]]></category>

		<guid isPermaLink="false">http://solutionizing.net/?p=872</guid>
		<description><![CDATA[In the spirit of &#8220;simplest thing that works,&#8221; my team has a rather low-fidelity approach to code reviews: patch files and e-mail. Nothing fancy, but we find it works rather well. It&#8217;s even easier thanks to git format-patch, which lets me easily generate a patch per commit, but I was never able to get send-email [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&#038;blog=3982353&#038;post=872&#038;subd=solutionizing&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In the spirit of &#8220;simplest thing that works,&#8221; my team has a rather low-fidelity approach to code reviews: patch files and e-mail. Nothing fancy, but we find it works rather well. It&#8217;s even easier thanks to <code>git format-patch</code>, which lets me easily generate a patch per commit, but I was never able to get <code>send-email</code> to work quite like I wanted. Instead, I whipped together a PowerShell script in a few minutes that does just the trick:</p>
<pre>function patch ($ref = 'master..', $Message = '', [switch]$KeepFiles) {
  $patchPaths = $(git format-patch -C -o C:/Temp/Patches $ref)
  if($patchPaths) {
    $outlook = New-Object -ComObject Outlook.Application
    $mail = $outlook.CreateItem(0)
    [void]$mail.Recipients.Add('myteam@mycompany.com')
    $mail.Subject = "Review - $Message"
    $commits = $(git log -C --pretty=format:'%s' --reverse $ref) | foreach {  "&lt;li&gt;$_&lt;/li&gt;" }
    $mail.HTMLBody = "&lt;ol style=`"font: 11pt Calibri`"&gt;$commits&lt;/ol&gt;"
    $patchPaths | foreach {
      [void]$mail.Attachments.Add($_)
      if(!$KeepFiles) { Remove-Item $_ }
    }
    $mail.Display()
  } else {
    Write-Warning 'Nothing to patch!'
  }
}</pre>
<h3>Usage:</h3>
<p>Create patch of everything on current branch since master:</p>
<pre>patch -m "Issue 123 - This is neat"</pre>
<p>Create patch of last two commits, without message:</p>
<pre>patch HEAD~2..</pre>
<p>Create patch of everything except the current commit, with message:</p>
<pre>patch master..HEAD~1 'Refactoring for Story 234'</pre>
<br /> Tagged: <a href='http://solutionizing.net/tag/format-patch/'>format-patch</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/solutionizing.wordpress.com/872/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/solutionizing.wordpress.com/872/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/solutionizing.wordpress.com/872/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/solutionizing.wordpress.com/872/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/solutionizing.wordpress.com/872/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/solutionizing.wordpress.com/872/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/solutionizing.wordpress.com/872/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/solutionizing.wordpress.com/872/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/solutionizing.wordpress.com/872/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/solutionizing.wordpress.com/872/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/solutionizing.wordpress.com/872/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/solutionizing.wordpress.com/872/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/solutionizing.wordpress.com/872/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/solutionizing.wordpress.com/872/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&#038;blog=3982353&#038;post=872&#038;subd=solutionizing&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://solutionizing.net/2010/12/05/code-review-with-git-patches-and-outlook-via-powershell/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/26483382e3717e58e4c45d06c8ec351d?s=96&#38;d=identicon&#38;r=PG" medium="image">
			<media:title type="html">dahlbyk</media:title>
		</media:content>
	</item>
		<item>
		<title>Git-Achievements in PowerShell</title>
		<link>http://solutionizing.net/2010/10/05/git-achievements-powershell/</link>
		<comments>http://solutionizing.net/2010/10/05/git-achievements-powershell/#comments</comments>
		<pubDate>Tue, 05 Oct 2010 15:00:20 +0000</pubDate>
		<dc:creator>Keith Dahlby</dc:creator>
				<category><![CDATA[Git]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[git-achievements]]></category>

		<guid isPermaLink="false">http://solutionizing.net/?p=832</guid>
		<description><![CDATA[Reading through Jason&#8217;s post on using Git-Achievements with msysGit, I couldn&#8217;t help but get it working with PowerShell. The result is a single PowerShell script added to my Git-Achievements repository, tagged here on the off chance I decided to upload my achievements. To install posh-git-achievements&#8230; Fork my repository on GitHub (or if you have an [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&#038;blog=3982353&#038;post=832&#038;subd=solutionizing&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Reading through Jason&#8217;s post on <a title="Git-Achievements on Windows" href="http://www.lostechies.com/blogs/jason_meridth/archive/2010/09/24/git-achievements-on-windows.aspx">using Git-Achievements with msysGit</a>, I couldn&#8217;t help but get it working with PowerShell. The result is a single PowerShell script added to <a title="dahlbyk's git-achievements" href="http://github.com/dahlbyk/git-achievements">my Git-Achievements repository</a>, tagged <a title="powershell on dahlbyk's git-achievements" href="http://github.com/dahlbyk/git-achievements/tree/powershell">here</a> on the off chance I decided to upload my achievements.</p>
<p>To install posh-git-achievements&#8230;</p>
<ol>
<li>Fork <a title="git-achievements on dahlbyk" href="http://github.com/dahlbyk/git-achievements">my repository</a> on GitHub (or if you have an existing repository, add me as a remote and pull)</li>
<li>Clone your fork of the repository (into C:\Git\git-achievements, for this example)</li>
<li>Open your <a href="http://technet.microsoft.com/en-us/library/ee692764.aspx">PowerShell profile</a> and add the following:<br />
<code>Set-Alias git C:\Git\git-achievements\git-achievements.ps1</code></li>
<li>&#8220;dot source&#8221; your profile to reload it in your current session (or just start a new session):<br />
<code>. $PROFILE</code></li>
<li>Check the install:<br />
<code>git achievements --help</code></li>
</ol>
<p>If all goes according to plan, this should unlock your first achievement.</p>
<p>Note that this will pass every <code>git</code> call through a few extra layers, including calls made for the posh-git prompt. But if you can tolerate the performance hit, it&#8217;s a rather fun way to expand your working knowledge of Git. Enjoy!</p>
<br /> Tagged: <a href='http://solutionizing.net/tag/git-achievements/'>git-achievements</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/solutionizing.wordpress.com/832/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/solutionizing.wordpress.com/832/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/solutionizing.wordpress.com/832/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/solutionizing.wordpress.com/832/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/solutionizing.wordpress.com/832/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/solutionizing.wordpress.com/832/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/solutionizing.wordpress.com/832/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/solutionizing.wordpress.com/832/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/solutionizing.wordpress.com/832/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/solutionizing.wordpress.com/832/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/solutionizing.wordpress.com/832/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/solutionizing.wordpress.com/832/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/solutionizing.wordpress.com/832/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/solutionizing.wordpress.com/832/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&#038;blog=3982353&#038;post=832&#038;subd=solutionizing&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://solutionizing.net/2010/10/05/git-achievements-powershell/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/26483382e3717e58e4c45d06c8ec351d?s=96&#38;d=identicon&#38;r=PG" medium="image">
			<media:title type="html">dahlbyk</media:title>
		</media:content>
	</item>
		<item>
		<title>posh-git Release v0.2</title>
		<link>http://solutionizing.net/2010/08/28/posh-git-release-v0-2/</link>
		<comments>http://solutionizing.net/2010/08/28/posh-git-release-v0-2/#comments</comments>
		<pubDate>Sat, 28 Aug 2010 17:20:19 +0000</pubDate>
		<dc:creator>Keith Dahlby</dc:creator>
				<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Git]]></category>
		<category><![CDATA[posh-git]]></category>

		<guid isPermaLink="false">http://solutionizing.net/?p=819</guid>
		<description><![CDATA[I just tagged the v0.2 release of posh-git, which you can download here. This is the last release supporing msysgit 1.6.5 and 1.7.0. In this release&#8230; PowerShell Module Thanks to a contribution from David Muhundro, posh-git now exposes its functions through a module (.psm1). The module exposes a number of functions whose usage can be [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&#038;blog=3982353&#038;post=819&#038;subd=solutionizing&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I just tagged the <a title="posh-git v0.2 on GitHub" href="http://github.com/dahlbyk/posh-git/tree/v0.2">v0.2 release</a> of <a title="posh-git on GitHub" href="http://github.com/dahlbyk/posh-git">posh-git</a>, which you can <a title="posh-git Downloads" href="http://github.com/dahlbyk/posh-git/downloads">download here</a>. This is the last release supporing msysgit 1.6.5 and 1.7.0. In this release&#8230;</p>
<h3>PowerShell Module</h3>
<p>Thanks to a contribution from <a href="http://www.mohundro.com/blog/">David Muhundro</a>, posh-git now exposes its functions through a module (.psm1). The module exposes a number of functions whose usage can be seen in the example profile.</p>
<h3>Tab Expansion Updates</h3>
<ul>
<li><a href="http://code.google.com/p/tortoisegit/">TortoiseGit</a> commands: <code>tgit &lt;tab&gt;</code></li>
<li>git-svn operations: <code>git svn &lt;tab&gt;</code></li>
<li>Stash completion for <code>git stash</code> operations: <code>show, apply, drop, pop, branch</code></li>
<li>Branch completion for <code>git reset</code> and <code>git rebase</code></li>
<li>Completion of deleted files for <code>git rm</code></li>
<li>For most commands, tab completion should now work if other command flags are in use. For example, <code>git rebase -i &lt;tab&gt;</code> works as expected.</li>
</ul>
<p>Thanks to <a href="http://www.jeremyskinner.co.uk/">Jeremy Skinner</a> and <a href="http://www.markembling.info/">Mark Embling</a> for their contributions to this release.</p>
<h3>Next Steps</h3>
<p>The most common complaint about posh-git is performance, which has already been addressed for the next release (available in my master branch). However, the fix requires taking a dependency on msysgit 1.7.1, which has not been officially released yet.  Still, it has been working fine for me.</p>
<p>Beyond that, we still need to address the first two items on my list from the last release&#8230;</p>
<ul>
<li>Testing! I&#8217;d like to figure out a way to run some integration tests  that verify a given repository state renders the expected prompt. If you  have suggestions how to approach this, or know how other Git  integration projects are tested, please let us know over at the <a href="http://groups.google.com/group/posh-git/">Google Group</a>.</li>
<li>Documentation! How to get started, what the project provides, etc.</li>
</ul>
<p>If you have any other feature requests or find issues, please let us know.</p>
<br /> Tagged: <a href='http://solutionizing.net/tag/git/'>Git</a>, <a href='http://solutionizing.net/tag/posh-git/'>posh-git</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/solutionizing.wordpress.com/819/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/solutionizing.wordpress.com/819/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/solutionizing.wordpress.com/819/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/solutionizing.wordpress.com/819/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/solutionizing.wordpress.com/819/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/solutionizing.wordpress.com/819/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/solutionizing.wordpress.com/819/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/solutionizing.wordpress.com/819/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/solutionizing.wordpress.com/819/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/solutionizing.wordpress.com/819/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/solutionizing.wordpress.com/819/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/solutionizing.wordpress.com/819/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/solutionizing.wordpress.com/819/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/solutionizing.wordpress.com/819/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&#038;blog=3982353&#038;post=819&#038;subd=solutionizing&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://solutionizing.net/2010/08/28/posh-git-release-v0-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/26483382e3717e58e4c45d06c8ec351d?s=96&#38;d=identicon&#38;r=PG" medium="image">
			<media:title type="html">dahlbyk</media:title>
		</media:content>
	</item>
		<item>
		<title>Elegant Inline Debug Tracing</title>
		<link>http://solutionizing.net/2009/04/14/elegant-inline-debug-tracing/</link>
		<comments>http://solutionizing.net/2009/04/14/elegant-inline-debug-tracing/#comments</comments>
		<pubDate>Wed, 15 Apr 2009 04:37:33 +0000</pubDate>
		<dc:creator>Keith Dahlby</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Object Model]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[SharePoint]]></category>
		<category><![CDATA[Debugging]]></category>
		<category><![CDATA[higher-order function]]></category>

		<guid isPermaLink="false">http://solutionizing.net/?p=500</guid>
		<description><![CDATA[As much fun as it is to step through code with a debugger, I usually prefer to use System.Diagnostics.Debug and Trace with DebugView to see what&#8217;s happening in realtime. This is particularly handy to track intermediate results in higher-order functions that you might not be able to step into. However, it&#8217;s not always convenient to [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&#038;blog=3982353&#038;post=500&#038;subd=solutionizing&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>As much fun as it is to step through code with a debugger, I usually prefer to use <a title="Debug Class (System.Diagnostics)" href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debug.aspx"><code>System.Diagnostics.Debug</code></a> and <a title="Trace Class (System.Diagnostics)" href="http://msdn.microsoft.com/en-us/library/system.diagnostics.trace.aspx"><code>Trace</code></a> with <a title="DebugView for Windows" href="http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx">DebugView</a> to see what&#8217;s happening in realtime. This is particularly handy to track intermediate results in higher-order functions that you might not be able to step into. However, it&#8217;s not always convenient to insert debugging statements amongst the composed expressions of F#, PowerShell or LINQ.</p>
<p>An alternative first came to mind while working in F#:</p>
<pre>let dbg x = System.Diagnostics.Debug.WriteLine(x |&gt; sprintf "%A"); x</pre>
<p>(Read <code>|&gt;</code> as &#8220;as next parameter to&#8221;.) We can then use this function anywhere to peek at a value, perhaps an intermediate list in this trivial example:</p>
<pre>let data = [1..10]
           |&gt; List.filter (fun i -&gt; i%3 = 0) |&gt; dbg
           |&gt; List.map (fun i -&gt; i*i)</pre>
<p>Indeed <code>[3; 6; 9]</code> are traced as multiples of three. Not a particularly convincing example, but it should be pretty easy to imagine a more complex algorithm for which unintrusive tracing would be useful.</p>
<p>This works pretty well with F#&#8217;s <code>|&gt;</code> operator to push values forward, but what about C#? Given my posting history, it shouldn&#8217;t be hard to guess where I&#8217;m going with this&#8230;</p>
<h3>Extension Methods</h3>
<p>So if <code>|&gt;</code> is &#8220;as next parameter to&#8221;, the <code>.</code> of an extension method call might read &#8220;as first parameter to&#8221;. So we can implement a roughly equivalent function (sans F#&#8217;s nice deep-print formatter <code>"%A"</code>) like so:</p>
<pre>    public static T Debug&lt;T&gt;(this T value)
    {
        Debug.WriteLine(value);
        return value;
    }

    public static T Dbg&lt;T&gt;(this T value, string category)
    {
        Debug.WriteLine(value, category);
        return value;
    }</pre>
<p><del datetime="2009-04-19T20:15:33+00:00">I find the optional label handy to keep different traces separate.</del> <ins datetime="2009-04-19T20:15:33+00:00">Looking again, there&#8217;s an overload that accepts a category, so we&#8217;ll use that instead.</ins> So why might this be useful? Maybe we want to log the value assigned within an object initializer:</p>
<pre>var q = new SPQuery() {
  Query = GetMyQuery().Debug("Query")
};</pre>
<p>Rather than store the query string to a temporary variable or retrieve the property after it&#8217;s been set, we can just trace the value inline. Or consider a LINQ example:</p>
<pre>var items = from SPListItem item in list.GetItems(q)
            let url = new SPFieldUrlValue(item["URL"] as string)
            where url.Url.Debug("URL").StartsWith(baseUrl, StringComparison.OrdinalIgnoreCase)
            select new
            {
                Title = item.Title.Debug("Title"),
                Description = url.Description,
            };</pre>
<p>Here we log all URLs that pass through, even the ones excluded from the result by the predicate. This would be much harder to implement efficiently without inline logging.</p>
<p>This technique works great for simple objects with a useful <code>ToString()</code>, but what about more complex objects? As has often been the answer lately, we can use higher-order functions:</p>
<pre>    public static T Dbg&lt;T, R&gt;(this T value, Func&lt;T, R&gt; selector)
    {
        Debug.WriteLine(selector(value));
        return value;
    }

    public static T Dbg&lt;T, R&gt;(this T value, string category, Func&lt;T, R&gt; selector)
    {
        Debug.WriteLine(selector(value), category);
        return value;
    }</pre>
<p>Now we can provide a delegate to trace whatever we want without affecting the object itself. For example, we can easily trace a row count for the <code>DataView</code> being returned:</p>
<pre>public DataView GetResults()
{
    var myTable = GetDataTable();
    // Process data...
    return myTable.DefaultView.Dbg("Result Count", v =&gt; v.Count);
}</pre>
<p>I could go on, but you get the idea.</p>
<h3>PowerShell Filter</h3>
<p>Finally, we can implement similar functionality in PowerShell using a filter with an optional scriptblock parameter:</p>
<pre>filter Debug([scriptblock] $sb = { $_ })
{
  [Diagnostics.Debug]::WriteLine((&amp; $sb))
  $_
}

PS &gt; 1..3 | Debug { $_*2 } | %{ $_*$_ }
1
4
9</pre>
<p>Which traces 2, 4, 6, as expected.</p>
<p><strong>Update 4/19/2009:</strong> Changed functions to use category overloads. And another point to consider: if the value being traced could be <code>null</code>, <code>selector</code> should be designed accordingly to avoid <code>NullReferenceException</code>. There&#8217;s nothing worse than bugs introduced by tracing or logging.</p>
<br /> Tagged: Debugging, higher-order function <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/solutionizing.wordpress.com/500/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/solutionizing.wordpress.com/500/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/solutionizing.wordpress.com/500/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/solutionizing.wordpress.com/500/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/solutionizing.wordpress.com/500/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/solutionizing.wordpress.com/500/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/solutionizing.wordpress.com/500/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/solutionizing.wordpress.com/500/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/solutionizing.wordpress.com/500/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/solutionizing.wordpress.com/500/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/solutionizing.wordpress.com/500/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/solutionizing.wordpress.com/500/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/solutionizing.wordpress.com/500/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/solutionizing.wordpress.com/500/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&#038;blog=3982353&#038;post=500&#038;subd=solutionizing&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://solutionizing.net/2009/04/14/elegant-inline-debug-tracing/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/26483382e3717e58e4c45d06c8ec351d?s=96&#38;d=identicon&#38;r=PG" medium="image">
			<media:title type="html">dahlbyk</media:title>
		</media:content>
	</item>
		<item>
		<title>SharePoint+PowerShell Leak Workarounds</title>
		<link>http://solutionizing.net/2009/02/16/sharepointpowershell-leak-workarounds/</link>
		<comments>http://solutionizing.net/2009/02/16/sharepointpowershell-leak-workarounds/#comments</comments>
		<pubDate>Tue, 17 Feb 2009 04:42:15 +0000</pubDate>
		<dc:creator>Keith Dahlby</dc:creator>
				<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[SharePoint]]></category>
		<category><![CDATA[dispose]]></category>
		<category><![CDATA[Threads]]></category>

		<guid isPermaLink="false">http://solutionizing.net/?p=435</guid>
		<description><![CDATA[Zach Rosenfield recently posted about an obscure memory leak issue when working with PowerShell and the SharePoint object model. You can read his post for details but in summary: PowerShell spawns a new thread for each pipeline (essentially any batch of code that runs together). SharePoint objects should not be used across multiple threads due [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&#038;blog=3982353&#038;post=435&#038;subd=solutionizing&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://sharepoint.microsoft.com/blogs/zach/">Zach Rosenfield</a> recently posted about an <a title="SharePoint+PowerShell is (Usually) a Perfect Match" href="http://sharepoint.microsoft.com/blogs/zach/Lists/Posts/Post.aspx?ID=34">obscure memory leak issue</a> when working with PowerShell and the SharePoint object model. You can read his post for details but in summary:</p>
<ol>
<li>PowerShell spawns a new thread for each pipeline (essentially any batch of code that runs together).</li>
<li>SharePoint objects should not be used across multiple threads due to mechanics of the unmanaged heap.</li>
<li>SharePoint objects used across multiple pipelines result in unmanaged heap leaks until PowerShell closes or you run out of memory.</li>
</ol>
<p>This PowerShell behavior is easy enough to verify:</p>
<pre>PS 1&gt; function Get-ThreadId { [Threading.Thread]::CurrentThread.ManagedThreadId }
PS 2&gt; set-alias gt Get-ThreadId
PS 3&gt; gt
6
PS 4&gt; gt
4</pre>
<p>So we need to ensure that our SharePoint objects are allocated, used and disposed within the same thread. How can we do this? Zach offers two suggestions, but there are actually several options:</p>
<h3>Single Line</h3>
<pre>PS 5&gt; gt; gt; gt
10
10
10
PS 6&gt; gt; `
&gt;&gt; gt; `
&gt;&gt; gt
&gt;&gt;
3
3
3</pre>
<h3>Script</h3>
<pre>PS 7&gt; @"
&gt;&gt; gt
&gt;&gt; gt
&gt;&gt; "@ &gt; gt.ps1
&gt;&gt;
PS 8&gt; .\gt.ps1
8
8</pre>
<h3>Function</h3>
<pre>PS 9&gt; function gt2 {
&gt;&gt; gt
&gt;&gt; gt
&gt;&gt; }
&gt;&gt;
PS 10&gt; gt2
4
4</pre>
<h3>Inline Script Block</h3>
<pre>PS 11&gt; &amp;{
&gt;&gt; gt
&gt;&gt; gt
&gt;&gt; }
&gt;&gt;
7
7</pre>
<h3>My <a title="Multi-Purpose PowerShell Using Function" href="http://solutionizing.net/2008/09/21/multi-purpose-powershell-using-function/">Using Function</a></h3>
<pre>PS 12&gt; using Microsoft.SharePoint
PS 13&gt; gt; using ($s = [Microsoft.SharePoint.SPSite] 'http://moss') {
&gt;&gt; gt
&gt;&gt; $s.Url
&gt;&gt; gt
&gt;&gt; }
&gt;&gt;
5
5

http://moss

5</pre>
<h3>Cmdlet + Wrapper Class</h3>
<p><a href="http://stsadm.blogspot.com/">Gary Lapointe</a> has a set of <a title="Downloads" href="http://stsadm.blogspot.com/2009/02/downloads.html">PowerShell cmdlets</a> that use <a title="Working with SPSite(Info) Objects Using PowerShell " href="http://stsadm.blogspot.com/2009/01/working-with-spsiteinfo-objects-using.html">wrapper objects</a> to hide SPSite/SPWeb objects unless you specifically ask for them.</p>
<pre>PS 14&gt; $spi = Get-SPSite-gl 'http://moss'
PS 15&gt; gt; using ($s = $spi.SPBase) { $s.Url; gt }
8

http://moss

8</pre>
<p>The severity of this issue depends on your environment and the kinds of scripts you&#8217;re running, but in memory-sensitive and production environments these are definitely some techniques to keep in mind.</p>
<br /> Tagged: dispose, Threads <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/solutionizing.wordpress.com/435/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/solutionizing.wordpress.com/435/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/solutionizing.wordpress.com/435/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/solutionizing.wordpress.com/435/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/solutionizing.wordpress.com/435/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/solutionizing.wordpress.com/435/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/solutionizing.wordpress.com/435/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/solutionizing.wordpress.com/435/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/solutionizing.wordpress.com/435/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/solutionizing.wordpress.com/435/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/solutionizing.wordpress.com/435/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/solutionizing.wordpress.com/435/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/solutionizing.wordpress.com/435/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/solutionizing.wordpress.com/435/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&#038;blog=3982353&#038;post=435&#038;subd=solutionizing&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://solutionizing.net/2009/02/16/sharepointpowershell-leak-workarounds/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/26483382e3717e58e4c45d06c8ec351d?s=96&#38;d=identicon&#38;r=PG" medium="image">
			<media:title type="html">dahlbyk</media:title>
		</media:content>
	</item>
		<item>
		<title>PowerShell Get-Type: Simplified Generics</title>
		<link>http://solutionizing.net/2009/01/01/powershell-get-type-simplified-generics/</link>
		<comments>http://solutionizing.net/2009/01/01/powershell-get-type-simplified-generics/#comments</comments>
		<pubDate>Fri, 02 Jan 2009 02:04:01 +0000</pubDate>
		<dc:creator>Keith Dahlby</dc:creator>
				<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Generic Type]]></category>
		<category><![CDATA[Get-Type]]></category>
		<category><![CDATA[New-GenericObject]]></category>

		<guid isPermaLink="false">http://solutionizing.net/?p=281</guid>
		<description><![CDATA[PowerShell doesn&#8217;t include any syntactic sugar for dealing with generic objects, so a number of people have posted code snippets online showing how to create generic lists, dictionaries, etc. Interestingly, nobody has pointed out that the real problem isn&#8217;t creating the objects—New-Object does that without issue (for the most part)—but simply that it&#8217;s tedious to [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&#038;blog=3982353&#038;post=281&#038;subd=solutionizing&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>PowerShell doesn&#8217;t include any syntactic sugar for dealing with generic objects, so a number of people have posted code snippets online showing how to create generic lists, dictionaries, etc. Interestingly, nobody has pointed out that the real problem isn&#8217;t creating the objects—New-Object does that without issue (for the most part)—but simply that it&#8217;s tedious to build correct closed type references for generics. This post attempts to address this core problem.</p>
<p>If we leverage the <code>$args</code> array, a trivial solution is quickly discovered:</p>
<pre>function TypeOf-Generic ([type] $base) {
  $base.MakeGenericType($args)
}</pre>
<p>Which is quite simple to use:</p>
<pre>$intList = New-Object (TypeOf-Generic System.Collections.Generic.List int)</pre>
<p>However, a bit more code yields a more complete solution:</p>
<pre>function global:Get-Type (
    $type = $(throw "Please specify a type")
    )
{
  trap [System.Management.Automation.RuntimeException] { throw ($_.Exception.Message) }

  if($args -and $args.Count -gt 0)
  {
    $types = $args[0] -as [type[]]
    if(-not $types) { $types = [type[]] $args }

    if($genericType = [type] ($type + '`' + $types.Count))
    {
      $genericType.MakeGenericType($types)
    }
  }
  else
  {
    [type] $type
  }
}</pre>
<p>Trapping <code>RuntimeException</code> allows us to repackage failed casts without the full <code>ErrorRecord</code>. We get a bit of usage flexibility by accepting our type arguments in either a single array or as the full <code>$args</code> array. With this function, all of the following will return valid types:</p>
<pre>$a = Get-Type ([System.Collections.ArrayList])
$b = Get-Type System.Collections.Hashtable
$c = Get-Type System.Collections.Generic.List int
$d = Get-Type System.Collections.Generic.Dictionary int,string
$e = Get-Type System.Collections.Generic.Dictionary int $d</pre>
<p>Corresponding to:</p>
<pre>System.Collections.ArrayList
System.Collections.Hashtable
System.Collections.Generic.List`1[System.Int32]
System.Collections.Generic.Dictionary`2[System.Int32,System.String]
System.Collections.Generic.Dictionary`2[System.Int32,System.Collections.Generic.Dictionary`2[System.Int32,System.String]]</pre>
<p>Having delegated the responsibility of resolving type references, we can update <a href="http://www.leeholmes.com/blog/default.aspx">Lee Holmes</a>&#8216;s <a title="Creating Generic Types in PowerShell" href="http://www.leeholmes.com/blog/CreatingGenericTypesInPowerShell.aspx"><code>New-GenericObject</code></a>:</p>
<pre>function New-GenericObject(
    $type = $(throw "Please specify a type"),
    [object[]] $typeParameters = $null,
    [object[]] $constructorParameters = @()
    )
{
    $closedType = (Get-Type $type $typeParameters)
    ,[Activator]::CreateInstance($closedType, $constructorParameters)
}</pre>
<p>I&#8217;ve included a few extra tweaks:</p>
<ol>
<li>I replaced <code>[string] $typeName</code> with <code>[object] $type</code> and changed <code>$typeParameters</code> from <code>[string[]]</code> to <code>[object[]]</code>, specifically to accept <code>[type]</code> values if they are provided.</li>
<li>If <code>$typeParameters</code> is <code>$null</code>, I assume we were passed a closed type; if not, <code>Get-Type</code> fails accordingly.</li>
<li><code>$constructorParameters</code> needs a default value to get around this exception:<br />
<blockquote><p>Exception calling &#8220;CreateInstance&#8221; with &#8220;2&#8243; argument(s): &#8220;Ambiguous match found.&#8221;</p></blockquote>
</li>
</ol>
<h3>Cross-Assembly Generics</h3>
<p>A user on Stack Overflow found an <a title="Powershell Generic Collections" href="http://stackoverflow.com/questions/184476">interesting quirk</a> when trying to instantiate a generic <code>SortedDictionary</code> in PowerShell. The problem is easy to reproduce:</p>
<pre>PS 1&gt; $sdt = Get-Type System.Collections.Generic.SortedDictionary string,string
PS 2&gt; $sdt.FullName
System.Collections.Generic.SortedDictionary`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToke
n=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
PS 3&gt; $sd = New-Object $sdt
New-Object : Cannot find type [System.Collections.Generic.SortedDictionary`2[System.String,System.String]]: make sure t
he assembly containing this type is loaded.
At line:1 char:17
+ $sd = New-Object  &lt;&lt;&lt;&lt; $sdt</pre>
<p>Yet the type works fine with <code>New-GenericObject</code>:</p>
<pre>PS 4&gt; $sd = New-GenericObject $sdt
PS 5&gt; $sd.GetType().FullName
System.Collections.Generic.SortedDictionary`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToke
n=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]</pre>
<p>As the answer on Stack Overflow points out, <code>SortedDictionary</code> and <code>System.String</code> live in different assemblies (System.dll and mscorlib.dll, respectively), which apparently confuses the PowerShell type converter. And because <code>New-Object</code> expects <code>-typeName</code> to be a string, it automatically casts our <code>[type]</code> object (which has the necessary assembly information) back to <code>[string]</code>:</p>
<pre>PS 6&gt; [string] $sdt
System.Collections.Generic.SortedDictionary`2[System.String,System.String]</pre>
<p>If we pass in the type&#8217;s <code>FullName</code> instead, everything works as expected:</p>
<pre>PS 7&gt; $sd2 = New-Object $sdt.FullName
PS 8&gt; $sd2.GetType().FullName
System.Collections.Generic.SortedDictionary`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToke
n=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]</pre>
<p>Note that this behavior extends to all assemblies, not just within the <code>System</code> namespace:</p>
<pre>PS 11&gt; $l = New-Object (Get-Type System.Collections.Generic.List ([Microsoft.SharePoint.SPWeb]))
New-Object : Cannot find type [System.Collections.Generic.List`1[Microsoft.SharePoint.SPWeb]]: make sure the assembly c
ontaining this type is loaded.
At line:1 char:16
+ $l = New-Object  &lt;&lt;&lt;&lt; (Get-Type System.Collections.Generic.List ([Microsoft.SharePoint.SPWeb]))
PS 12&gt; $l = New-Object (Get-Type System.Collections.Generic.List ([Microsoft.SharePoint.SPWeb])).FullName
PS 13&gt; $l.GetType().FullName
System.Collections.Generic.List`1[[Microsoft.SharePoint.SPWeb, Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral,
 PublicKeyToken=71e9bce111e9429c]]</pre>
<p>If someone on the PowerShell team reads this, it would be awesome if New-Object had a parameter set that accepted a [type] instead of a [string]. Thanks in advance!</p>
<br /> Tagged: Generic Type, Get-Type, New-GenericObject <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/solutionizing.wordpress.com/281/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/solutionizing.wordpress.com/281/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/solutionizing.wordpress.com/281/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/solutionizing.wordpress.com/281/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/solutionizing.wordpress.com/281/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/solutionizing.wordpress.com/281/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/solutionizing.wordpress.com/281/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/solutionizing.wordpress.com/281/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/solutionizing.wordpress.com/281/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/solutionizing.wordpress.com/281/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/solutionizing.wordpress.com/281/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/solutionizing.wordpress.com/281/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/solutionizing.wordpress.com/281/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/solutionizing.wordpress.com/281/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&#038;blog=3982353&#038;post=281&#038;subd=solutionizing&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://solutionizing.net/2009/01/01/powershell-get-type-simplified-generics/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/26483382e3717e58e4c45d06c8ec351d?s=96&#38;d=identicon&#38;r=PG" medium="image">
			<media:title type="html">dahlbyk</media:title>
		</media:content>
	</item>
		<item>
		<title>PowerShell Coalesce and PowerShellASP Query String Parameters</title>
		<link>http://solutionizing.net/2008/12/20/powershell-coalesce-and-powershellasp-query-string-parameters/</link>
		<comments>http://solutionizing.net/2008/12/20/powershell-coalesce-and-powershellasp-query-string-parameters/#comments</comments>
		<pubDate>Sun, 21 Dec 2008 04:03:19 +0000</pubDate>
		<dc:creator>Keith Dahlby</dc:creator>
				<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Coalesce]]></category>
		<category><![CDATA[PowerShellASP]]></category>
		<category><![CDATA[PowerShellPages]]></category>
		<category><![CDATA[Query String]]></category>

		<guid isPermaLink="false">http://solutionizing.net/?p=259</guid>
		<description><![CDATA[I had fun initially with PowerShellASP, but its sealed classes prevented me from doing much useful with it in SharePoint. I really need to take a look at Andre de Cavaignac&#8216;s PowerShellPages project, though the GPL license is a bit restrictive for my taste. Maybe I&#8217;ll just build my own&#8230; Anyway, I actually had a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&#038;blog=3982353&#038;post=259&#038;subd=solutionizing&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I had fun initially with <a href="http://www.powershelltoys.com/">PowerShellASP</a>, but its sealed classes prevented me from doing much useful with it in SharePoint. I really need to take a look at <a href="http://decav.com/blogs/andre/default.aspx">Andre de Cavaignac</a>&#8216;s <a title="Introducing PowerShell Pages - Script Style HTML Rendering" href="http://decav.com/blogs/andre/archive/2008/07/05/introducing-powershell-pages-script-style-html-rendering.aspx">PowerShellPages</a> <a title="PowerShell Pages @ CodePlex" href="http://www.codeplex.com/PowerShellPages">project</a>, though the GPL license is a bit restrictive for my taste. Maybe I&#8217;ll just build my own&#8230;</p>
<p>Anyway, I actually had a practical use for PoShASP today, and in working with it I decided there needed to be a better way to handle QueryString values. The resulting function is fairly straight-forward, and supports typed and optional parameters:</p>
<pre>&lt;% QSParam w x,int,10 y,double z,zzz %&gt;
w = &lt;%= $w %&gt;
x = &lt;%= $x %&gt;
y = &lt;%= $y %&gt;
z = &lt;%= $z %&gt;</pre>
<p>With no query string, we get the following:</p>
<pre>w =
x = 10
y =
z = zzz</pre>
<p>However, if I use a query string like w=42&amp;x=oops&amp;y=3.14&amp;z=pi, the valid values fall through:</p>
<pre>w = 42
x = 10
y = 3.14
z = pi</pre>
<p>Since &#8216;oops&#8217; isn&#8217;t an [int], we get the default. But first&#8230;</p>
<h2>PowerShell Coalesce</h2>
<p>One of the most underused C# operators is the coalesce operator (<code>??</code>), which evaluates to the right-hand value if the left-hand value is null. PowerShell doesn&#8217;t include such an operator (to my knowledge), but we can certainly build a function to do the job. I found an implementation contributed anonymously in the comments <a title="Output Cardinality - Scalars, Collections and Empty Sets - Oh My!" href="http://keithhill.spaces.live.com/Blog/cns!5A8D2641E0963A97!816.entry#sn_ccComment2">here</a>:</p>
<pre>function Coalesce-Args {
    ([object[]]($args | ?{$_}) + ,$null)[0]
}</pre>
<p>Which can be simplified to this:</p>
<pre>function Coalesce-Args {
  (@($args | ?{$_}) + $null)[0]
}
Set-Alias ?? Coalesce-Args</pre>
<p>The array subexpression <code>@( ... )</code> always returns an array, to which we append <code>$null</code> in case the array is empty. Taking the first element yields the desired result. I also define an alias (<code>??</code>) for an easily remembered shorthand, though the usage is different from the binary C# operator. With our new function, my <a title="JSON Factory" href="http://solutionizing.net/2008/08/06/powershellasp-applied-json-factory/">original QueryString pattern</a>:</p>
<pre>if( !($n = $Request.QueryString["n"] -as [int]) ) { $n = 10 }</pre>
<p>Can be rewritten as:</p>
<pre>$n = ?? ($Request.QueryString["n"] -as [int]) 10</pre>
<h2>QSParam Function</h2>
<p>Now that we have <code>Coalesce-Args</code>, we can implement <code>QSParam</code>:</p>
<pre>function QSParam {
  $QueryString = $Request.QueryString
  $args | ForEach-Object {
    $arg = @($_)
    $varName = $arg[0];
    $varType = $arg[1] -as [type];

    $qsValue = $QueryString[$varName]
    if ($varType -eq $null) {
      $varValue = Coalesce-Args $qsValue $arg[2] $arg[1]
    } else {
      $varValue = Coalesce-Args ($qsValue -as $varType) `
                                ($arg[2] -as $varType)
    }

    Set-Variable $varName $varValue -Scope script
  }
}</pre>
<p>If  PowerShell can&#8217;t cast the second value as a type, we use it as a default value. If a third value is specified, that takes priority over the second value (which is how you can specify a default value that would otherwise be confused for a type: <code>QSParam rhymesWithSquid,$null,guid</code>). Finally, we assign the result to a script-scoped variable so we don&#8217;t have to <a title="Running Windows PowerShell Scripts" href="http://www.microsoft.com/technet/scriptcenter/topics/winpsh/manual/run.mspx#EMBAC">dot source</a> the function call.</p>
<p>And in case you don&#8217;t follow the <a href="http://blogs.msdn.com/powershell/">PowerShell team blog</a> (or missed the post), Channel 9&#8242;s <a title="Erik Meijer and Jeffrey Snover" href="http://blogs.msdn.com/powershell/archive/2008/12/03/expert-to-expert-erik-meijer-and-jeffrey-snover-inside-powershell.aspx">Expert-to-Expert with Erik Meijer and Jeffrey Snover</a> is definitely worth watching if you&#8217;re at all interested in the language internals and other geeky stuff. Jeffrey&#8217;s enthusiasm for the language is infectious.</p>
<br /> Tagged: Coalesce, PowerShellASP, PowerShellPages, Query String <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/solutionizing.wordpress.com/259/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/solutionizing.wordpress.com/259/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/solutionizing.wordpress.com/259/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/solutionizing.wordpress.com/259/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/solutionizing.wordpress.com/259/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/solutionizing.wordpress.com/259/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/solutionizing.wordpress.com/259/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/solutionizing.wordpress.com/259/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/solutionizing.wordpress.com/259/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/solutionizing.wordpress.com/259/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/solutionizing.wordpress.com/259/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/solutionizing.wordpress.com/259/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/solutionizing.wordpress.com/259/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/solutionizing.wordpress.com/259/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&#038;blog=3982353&#038;post=259&#038;subd=solutionizing&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://solutionizing.net/2008/12/20/powershell-coalesce-and-powershellasp-query-string-parameters/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/26483382e3717e58e4c45d06c8ec351d?s=96&#38;d=identicon&#38;r=PG" medium="image">
			<media:title type="html">dahlbyk</media:title>
		</media:content>
	</item>
		<item>
		<title>PowerShell Dispose-All</title>
		<link>http://solutionizing.net/2008/12/12/powershell-dispose-all/</link>
		<comments>http://solutionizing.net/2008/12/12/powershell-dispose-all/#comments</comments>
		<pubDate>Fri, 12 Dec 2008 05:28:51 +0000</pubDate>
		<dc:creator>Keith Dahlby</dc:creator>
				<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[dispose]]></category>
		<category><![CDATA[Dispose-All]]></category>
		<category><![CDATA[IDisposable]]></category>

		<guid isPermaLink="false">http://solutionizing.net/?p=255</guid>
		<description><![CDATA[With all the talk of Dispose safety in object model code, it&#8217;s easy to forget that those same objects need to be cleaned up in PowerShell as well. Sure, SharePoint will clean everything up when the thread ends, but my PowerShell doesn&#8217;t get closed all that often, leaving open SPRequests for extended periods of time. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&#038;blog=3982353&#038;post=255&#038;subd=solutionizing&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>With all the talk of Dispose safety in object model code, it&#8217;s easy to forget that those same objects need to be cleaned up in PowerShell as well. Sure, SharePoint will clean everything up when the thread ends, but my PowerShell doesn&#8217;t get closed all that often, leaving open SPRequests for extended periods of time. To combat that, I wrote a quick function that will clean up all my IDisposable variables for me:</p>
<pre>function Dispose-All {
    Get-Variable -exclude Runspace |
        Where-Object {
            $_.Value -is [System.IDisposable]
        } |
        Foreach-Object {
            $_.Value.Dispose()
            Remove-Variable $_.Name
        }
}</pre>
<p>For some reason, I don&#8217;t think it would be a good idea to Dispose() the current Runspace&#8230; (Edit: Apparently I define $Runspace in a long-forgotten part of my profile script, so don&#8217;t be worried if you don&#8217;t have that defined.)</p>
<p>Of course this isn&#8217;t foolproof, as variables can be overwritten and not all IDisposables will have been assigned to variables in the first place, but you could certainly adapt your shell behavior to make the most out of a catch-all cleanup like this.</p>
<br /> Tagged: dispose, Dispose-All, IDisposable <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/solutionizing.wordpress.com/255/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/solutionizing.wordpress.com/255/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/solutionizing.wordpress.com/255/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/solutionizing.wordpress.com/255/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/solutionizing.wordpress.com/255/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/solutionizing.wordpress.com/255/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/solutionizing.wordpress.com/255/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/solutionizing.wordpress.com/255/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/solutionizing.wordpress.com/255/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/solutionizing.wordpress.com/255/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/solutionizing.wordpress.com/255/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/solutionizing.wordpress.com/255/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/solutionizing.wordpress.com/255/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/solutionizing.wordpress.com/255/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&#038;blog=3982353&#038;post=255&#038;subd=solutionizing&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://solutionizing.net/2008/12/12/powershell-dispose-all/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/26483382e3717e58e4c45d06c8ec351d?s=96&#38;d=identicon&#38;r=PG" medium="image">
			<media:title type="html">dahlbyk</media:title>
		</media:content>
	</item>
		<item>
		<title>Multi-Purpose PowerShell Using Function</title>
		<link>http://solutionizing.net/2008/09/21/multi-purpose-powershell-using-function/</link>
		<comments>http://solutionizing.net/2008/09/21/multi-purpose-powershell-using-function/#comments</comments>
		<pubDate>Sun, 21 Sep 2008 22:17:08 +0000</pubDate>
		<dc:creator>Keith Dahlby</dc:creator>
				<category><![CDATA[Object Model]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[IDisposable]]></category>
		<category><![CDATA[Load Assembly]]></category>
		<category><![CDATA[PowerShell Script Scope]]></category>
		<category><![CDATA[PowerShell Using]]></category>

		<guid isPermaLink="false">http://solutionizing.wordpress.com/?p=163</guid>
		<description><![CDATA[It&#8217;s always bothered me that there isn&#8217;t a clean way to deal with IDisposables in PowerShell. It seems Adam Weigert came to the same conclusion and implemented a using function much like the statement found in C# and VB. Note that he also makes use of his implementation of PowerShell try..catch..finally, which is pretty slick. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&#038;blog=3982353&#038;post=163&#038;subd=solutionizing&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s always bothered me that there isn&#8217;t a clean way to deal with IDisposables in PowerShell. It seems <a href="http://weblogs.asp.net/adweigert/">Adam Weigert</a> came to the same conclusion and implemented a <a title="Adding the Using Statement" href="http://weblogs.asp.net/adweigert/archive/2008/08/27/powershell-adding-the-using-statement.aspx"><code>using</code> function</a> much like the statement found in C# and VB. Note that he also makes use of his implementation of <a title="Try...Catch...Finally Comes To Life" href="http://weblogs.asp.net/adweigert/archive/2007/10/10/powershell-try-catch-finally-comes-to-life.aspx">PowerShell <code>try..catch..finally</code></a>, which is pretty slick. Meanwhile, I&#8217;m told <a href="http://www.iwkid.com/blog/">Raymond Mitchell</a> has his own <code>using</code> function that he uses to load assemblies, which certainly makes sense to me.</p>
<p>I figure the next evolution is to provide a generic <code>using</code> that covers all the bases:</p>
<pre>function using {
    param (
        $inputObject = $(throw "The parameter -inputObject is required."),
        [ScriptBlock] $scriptBlock
    )

    if ($inputObject -is [string]) {
        if (Test-Path $inputObject) {
            [system.reflection.assembly]::LoadFrom($inputObject)
        } elseif($null -ne (
              new-object System.Reflection.AssemblyName($inputObject)
              ).GetPublicKeyToken()) {
            [system.reflection.assembly]::Load($inputObject)
        } else {
            [system.reflection.assembly]::LoadWithPartialName($inputObject)
        }
    } elseif ($inputObject -is [System.IDisposable] -and $scriptBlock -ne $null) {
        Try {
            &amp;$scriptBlock
        } -Finally {
            if ($inputObject -ne $null) {
                $inputObject.Dispose()
            }
            Get-Variable -scope script |
                Where-Object {
                    [object]::ReferenceEquals($_.Value.PSBase, $inputObject.PSBase)
                } |
                Foreach-Object {
                    Remove-Variable $_.Name -scope script
                }
        }
    } else {
        $inputObject
    }
}</pre>
<p>Some notes on the code:</p>
<ul>
<li>If <code>$inputObject</code> is a string, I assume it&#8217;s an assembly reference&#8230;
<ul>
<li>If the string is a path, load as a path</li>
<li>Rather than parse the string, I figure the framework knows best; the presence of a PublicKeyToken means it&#8217;s probably a full assembly name</li>
<li>I considered adding support for <a title="How do I easily load assemblies, when LoadWithPartialName has been deprecated?" href="http://www.leeholmes.com/blog/HowDoIEasilyLoadAssembliesWhenLoadWithPartialNameHasBeenDeprecated.aspx">this alternative</a> to <code>LoadWithPartialName</code>, but I don&#8217;t feel like managing a global &#8220;assembly map&#8221;; the deprecated shortcut will have to do for now</li>
</ul>
</li>
<li>If <code>$inputObject</code> is <code>IDisposable</code> and a script block was supplied&#8230;
<ul>
<li>Wrap script execution in <code>Try..Finally</code> to make sure we get to <code>Dispose()</code></li>
<li>Here I disagree with Adam &#8211; if the PSObject&#8217;s Dispose method was overridden, we should assume it was done for good reason (more on this in a later post) and that the override will respect the object&#8217;s disposability.</li>
<li>After disposal, I thought it might be nice to take the variable out of scope like C#/VB. Using <code>-scope script</code> will look at variables in the scope where our function was called, and since we don&#8217;t know what <code>$inputObject</code> was named before it was passed in, I just compare references instead.</li>
</ul>
</li>
<li>Otherwise just punt the object along in the pipeline</li>
</ul>
<h3>Usage</h3>
<p>Loading assemblies is pretty straightforward:</p>
<pre>using System.Windows.Forms
using 'System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
using C:\Dev\DisposeTest\bin\Debug\DisposeTest.dll</pre>
<p>To test <code>IDisposable</code> handling, I use a simple disposable object which returns its hash code in <code>ToString()</code>, instantiated by a helper function:</p>
<pre>function new-disp { new-object DisposeTest.Disposable }</pre>
<p>To verify that variable scope is handled properly, we need two test scripts. <code>gv</code> is an alias for <code>Get-Variable</code>.</p>
<h4>NestedTest.ps1</h4>
<pre>gv x
using ($x = new-disp) { gv x }
gv x</pre>
<h4>UsingTest.ps1</h4>
<pre>$x = 'X'
.\NestedTest.ps1
using ($y = new-disp) { gv y }
gv y</pre>
<p>From the behavior in C#/VB, we expect that the object being &#8216;used&#8217; will only be available within the scope of the script block. So when we enter NestedTest.ps1, we should see the <code>$x</code> remains &#8216;X&#8217;, inherited from the parent scope, both before and after the <code>using</code> statement. Similarly, we expect <code>$y</code> will not be accessible outside of the <code>using</code> block:</p>
<p><a href="http://solutionizing.files.wordpress.com/2008/09/usingtest.png"><img class="alignnone size-full wp-image-170" title="Results of UsingTest.ps1" src="http://solutionizing.files.wordpress.com/2008/09/usingtest.png?w=780" alt=""   /></a></p>
<h4>SharePoint Example</h4>
<pre>using Microsoft.SharePoint
using ($s = new-object Microsoft.SharePoint.SPSite('http://localhost/')) {
  $s.AllWebs | %{ using ($_) { $_ | select Title, Url } }
}
if($s -eq $null) { 'Success!' }</pre>
<p>It&#8217;s not exceedingly friendly for interactive mode, particularly for tab completion, but it should aid script readability.</p>
<br /> Tagged: IDisposable, Load Assembly, PowerShell Script Scope, PowerShell Using <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/solutionizing.wordpress.com/163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/solutionizing.wordpress.com/163/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/solutionizing.wordpress.com/163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/solutionizing.wordpress.com/163/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/solutionizing.wordpress.com/163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/solutionizing.wordpress.com/163/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/solutionizing.wordpress.com/163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/solutionizing.wordpress.com/163/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/solutionizing.wordpress.com/163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/solutionizing.wordpress.com/163/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/solutionizing.wordpress.com/163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/solutionizing.wordpress.com/163/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/solutionizing.wordpress.com/163/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/solutionizing.wordpress.com/163/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&#038;blog=3982353&#038;post=163&#038;subd=solutionizing&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://solutionizing.net/2008/09/21/multi-purpose-powershell-using-function/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/26483382e3717e58e4c45d06c8ec351d?s=96&#38;d=identicon&#38;r=PG" medium="image">
			<media:title type="html">dahlbyk</media:title>
		</media:content>

		<media:content url="http://solutionizing.files.wordpress.com/2008/09/usingtest.png" medium="image">
			<media:title type="html">Results of UsingTest.ps1</media:title>
		</media:content>
	</item>
		<item>
		<title>PowerShellASP Applied: JSON Factory</title>
		<link>http://solutionizing.net/2008/08/06/powershellasp-applied-json-factory/</link>
		<comments>http://solutionizing.net/2008/08/06/powershellasp-applied-json-factory/#comments</comments>
		<pubDate>Wed, 06 Aug 2008 23:04:06 +0000</pubDate>
		<dc:creator>Keith Dahlby</dc:creator>
				<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[SharePoint]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[PowerShellASP]]></category>

		<guid isPermaLink="false">http://solutionizing.wordpress.com/?p=83</guid>
		<description><![CDATA[Now that we can use PowerShellASP with SharePoint, what can we do with it? Well without master page or web part support, we can&#8217;t easily integrate PoShASP content directly into the SharePoint experience. Fortunately, we can leverage PowerShell in other ways. An easy example is generating JSON, perhaps from the PowerShell standby Get-Process: &#60;% $Response.ContentType [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&#038;blog=3982353&#038;post=83&#038;subd=solutionizing&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Now that we can use <a href="http://www.powershelltoys.com/">PowerShellASP</a> <a href="http://solutionizing.net/2008/07/24/powershellasp-with-sharepoint/">with SharePoint</a>, what can we do with it? Well without master page or web part support, we can&#8217;t easily integrate PoShASP content directly into the SharePoint experience. Fortunately, we can leverage PowerShell in other ways. An easy example is generating <a title="JavaScript Object Notation" href="http://json.org/">JSON</a>, perhaps from the PowerShell standby <code>Get-Process</code>:</p>
<pre>&lt;% $Response.ContentType = "application/json; charset=utf-8" %&gt;
&lt;% $Response.Cache.SetCacheability([System.Web.HttpCacheability]'NoCache') %&gt;
&lt;% $Response.Cache.SetExpires([DateTime]::MinValue) %&gt;
&lt;% if( !($n = $Request.QueryString["n"] -as [int]) ) { $n = 10 } %&gt;
{"processes":[
  &lt;% [string]::Join(",`n  ",
  (get-process | sort ws -desc | select -first $n | foreach {
  "{'ID':$($_.ID),'Name':'$($_.Name)','WS':$($_.ws)}" })) %&gt;
]}</pre>
<p>After we set the JSON ContentType and cache policy, we try to fetch an &#8220;n&#8221; query parameter. If n is missing or not a number, we default to 10. Now we can start building our JSON object. To build our array, we use <code>System.String</code>&#8216;s static <code>Join</code> method (the backtick is PowerShell&#8217;s escape character, so <code>`n</code> is a newline). <code>Join</code>&#8216;s <code>string[]</code> parameter is provided by a PowerShell pipeline that fetches our system processes, sorts by working set size, selects the top <code>$n</code> and then iterates through those process objects, returning a string of JSON with our desired properties. Note also that PoShASP seems to require an empty line at the end of the file, otherwise &#8220;]}&#8221; is ignored. Our output will look something like this:</p>
<pre>{"processes":[
  {'ID':1672,'Name':'sqlservr','WS':506028032},
  {'ID':3296,'Name':'devenv','WS':230555648},
  {'ID':4720,'Name':'w3wp','WS':181100544},
  {'ID':376,'Name':'services','WS':121995264},
  {'ID':3372,'Name':'w3wp','WS':102522880}
]}</pre>
<p>Let&#8217;s save our JSON endpoint as %12%\TEMPLATE\LAYOUTS\Get-Process.json.ps1x, which we can test by visiting http://server/_layouts/Get-Process.json.ps1x?n=5. Now it&#8217;s AJAX time! Since not everyone can use the ASP.NET AJAX Extensions, we&#8217;ll just do it the old-fashioned way. Starting with a Content Editor Web Part on a page of your choice, set the source to the following:</p>
<pre>&lt;div id="d_procs"&gt;
&lt;img src="/_layouts/images/GEARS_AN.GIF"
  alt="Loading..." align="center" /&gt;
&lt;/div&gt;
&lt;script&gt;
function getXmlHttpRequestObject() {
 if (window.XMLHttpRequest) {
  return new XMLHttpRequest();
 } else if(window.ActiveXObject) {
  return new ActiveXObject("Microsoft.XMLHTTP");
 } else {
  document.getElementById('d_procs').innerHTML =
  'Cound not create XmlHttpRequest Object.';
 }
}

var r = getXmlHttpRequestObject();
var c = 0;
var mTimer;

function getProcs() {
 if (r.readyState == 4 || r.readyState == 0) {
  r.open("GET", '/_layouts/Get-Process.json.ps1x?n=5', true);
  r.onreadystatechange = handleReceiveProcs;
  r.send(null);
 }
}

function handleReceiveProcs() {
 if (r.readyState == 4) {
  var d = document.getElementById('d_procs');
  var response = eval("(" + r.responseText + ")");
  var p = response.processes;
  var t = "&lt;table width=\"100%\"&gt;";
  t += "&lt;tr&gt;&lt;th&gt;ID&lt;/th&gt;&lt;th&gt;Name&lt;/th&gt;&lt;th&gt;WS(MB)&lt;/th&gt;&lt;/tr&gt;";
  for(i=0;i &lt; p.length; i++) {
   t += '&lt;tr&gt;&lt;td&gt;'+p[i]['ID']+'&lt;/td&gt;';
   t += '&lt;td&gt;'+p[i]['Name']+'&lt;/td/&gt;';
   t += '&lt;td align=\"right\"&gt;';
   t += (p[i]['WS']/(1024*1024.0)).toFixed(2);
   t += '&lt;/td/&gt;&lt;/tr&gt;';
  }
  t += "&lt;/table&gt;&lt;p&gt;Refresh count: "+(++c)+"&lt;/p&gt;";
  d.innerHTML = t;
  mTimer = setTimeout('getProcs();', 3000); // 3-sec refresh
 }
}

_spBodyOnLoadFunctionNames.push('getProcs');
&lt;/script&gt;</pre>
<p>I haven&#8217;t put much effort into cleaning up the code, but it does the job (in FF2 and IE7, at least):<br />
<a href="http://solutionizing.files.wordpress.com/2008/08/poshasp-json-webpart.png"><img class="alignnone size-full wp-image-86" src="http://solutionizing.files.wordpress.com/2008/08/poshasp-json-webpart.png?w=780" alt=""   /></a></p>
<p>With PowerShell&#8217;s ease of development and specialized adapters, this is just the tip of the iceberg. What other real-time data would you find useful?</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/solutionizing.wordpress.com/83/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/solutionizing.wordpress.com/83/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/solutionizing.wordpress.com/83/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/solutionizing.wordpress.com/83/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/solutionizing.wordpress.com/83/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/solutionizing.wordpress.com/83/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/solutionizing.wordpress.com/83/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/solutionizing.wordpress.com/83/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/solutionizing.wordpress.com/83/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/solutionizing.wordpress.com/83/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/solutionizing.wordpress.com/83/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/solutionizing.wordpress.com/83/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/solutionizing.wordpress.com/83/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/solutionizing.wordpress.com/83/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/solutionizing.wordpress.com/83/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/solutionizing.wordpress.com/83/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&#038;blog=3982353&#038;post=83&#038;subd=solutionizing&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://solutionizing.net/2008/08/06/powershellasp-applied-json-factory/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/26483382e3717e58e4c45d06c8ec351d?s=96&#38;d=identicon&#38;r=PG" medium="image">
			<media:title type="html">dahlbyk</media:title>
		</media:content>

		<media:content url="http://solutionizing.files.wordpress.com/2008/08/poshasp-json-webpart.png" medium="image" />
	</item>
	</channel>
</rss>
