<?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/"
	>

<channel>
	<title>Yeah it&#039;s a blog &#187; PowerShell</title>
	<atom:link href="http://www.owenpellegrin.com/blog/category/powershell/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.owenpellegrin.com</link>
	<description>I write stuff here</description>
	<lastBuildDate>Fri, 02 Jul 2010 21:25:48 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Weird Terminating Error Behavior</title>
		<link>http://www.owenpellegrin.com/blog/powershell/weird-terminating-error-behavior/</link>
		<comments>http://www.owenpellegrin.com/blog/powershell/weird-terminating-error-behavior/#comments</comments>
		<pubDate>Thu, 24 Jul 2008 20:02:40 +0000</pubDate>
		<dc:creator>Owen Pellegrin</dc:creator>
				<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://www.atmaweapon.org/blog/?p=32</guid>
		<description><![CDATA[I&#8217;m writing a dirty hack PowerShell provider so that I can have a reasonable base of knowledge before approaching something more work-oriented.&#160; One component of the path the provider accepts must be an integer, so I decided to throw a terminating error if the path does not follow this rule. I also decided I&#8217;d do [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m writing a dirty hack PowerShell provider so that I can have a reasonable base of knowledge before approaching something more work-oriented.&#160; One component of the path the provider accepts must be an integer, so I decided to throw a terminating error if the path does not follow this rule. I also decided I&#8217;d do this so I could examine how terminating errors are handled. Something that mystifies me is the terminating error isn&#8217;t behaving as I understand it.&#160; Here&#8217;s the code I use to throw the error:</p>
<pre class="code">var record = new ErrorRecord(new ArgumentException(&quot;path&quot;), &quot;InvalidItemIndex&quot;,
                           ErrorCategory.InvalidArgument, null);
var details = new ErrorDetails(&quot;The second element of a text file path must be an integer.&quot;);
record.ErrorDetails = details;
ThrowTerminatingError(record);</pre>
<p>I expect that I&#8217;d see the information in the <em>ErrorDetails</em> property in some way, based on how the documentation is written; instead it seems like this information gets lost somewhere:</p>
<pre class="code">PS C:\Documents and Settings\myUsername\My Documents&gt; get-item text:\Section1\item1
Get-Item : The second component of the path must be an integer.
At line:1 char:9
+ get-item  &lt;&lt;&lt;&lt; text:\Section1\item1
PS C:\Documents and Settings\myUsername\My Documents&gt; $error[0].ErrorDetails -eq $null
True
PS C:\Documents and Settings\myUsername\My Documents&gt;</pre>
<p>Maybe it&#8217;s fixed in PowerShell v.2.0, or maybe I&#8217;m doing something wrong, but this is definitely not what I expected.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.owenpellegrin.com/blog/powershell/weird-terminating-error-behavior/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Writing Objects from PowerShell Scripts</title>
		<link>http://www.owenpellegrin.com/blog/powershell/writing-objects-from-powershell-scripts/</link>
		<comments>http://www.owenpellegrin.com/blog/powershell/writing-objects-from-powershell-scripts/#comments</comments>
		<pubDate>Wed, 23 Jul 2008 15:19:41 +0000</pubDate>
		<dc:creator>Owen Pellegrin</dc:creator>
				<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://www.atmaweapon.org/blog/?p=30</guid>
		<description><![CDATA[I&#8217;m going to continue writing about PowerShell because it&#8217;s fun to talk about and fun to use. Today I decided to try and analyze some data in text files using a PowerShell script. The files were simulations of a betting strategy in a coin-toss scenario. The first line represented the final balance and every line [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m going to continue writing about PowerShell because it&#8217;s fun to talk about and fun to use.</p>
<p>Today I decided to try and analyze some data in text files using a PowerShell script. The files were simulations of a betting strategy in a coin-toss scenario. The first line represented the final balance and every line thereafter represented the balance after a bet was completed. I was interested in the average balance over time and the average minimum balance for all files. The script itself was pretty uninteresting until I got to the output:</p>
<pre class="code">$files = get-childitem *.txt
$sum = 0
$count = 0
$minSum = 0

foreach ($file in $files)
{
    Write-Verbose &quot;Processing file: $file&quot;
    $sum += [long](get-content $file -totalCount 1)
    $count += 1

    $values = get-content $file
    $minimum = 0

    foreach ($line in $values)
    {
        $value = [int]$line
        $minimum = [Math]::Min($value, $minimum)
    }

    $minSum += $minimum
}

$average = $sum / $count
$averageMinimum = $minSum / $count</pre>
<p>Now is when it gets fun. I originally just wrote the output using <em>write-output</em>:</p>
<pre class="code">write-output &quot;Average: $average&quot;
write-output &quot;MinAverage: $minAverage&quot;</pre>
<p>This didn&#8217;t seem very PowerShell-like. I wanted to output an object that could be used by other scripts (for the heck of it at least.) I knew how to do this from a cmdlet, but had to search to find how to do it from a script. There seems to be two ways to make objects or object-like things to write.</p>
<h5>Associative Arrays</h5>
<p>Perl hackers love their hashes, and with good reason: this little data structure is very powerful. In the .NET world, we call them &quot;dictionaries&quot; for some reason. PowerShell associative arrays are declared with this syntax:</p>
<pre class="code">$array = @{name = value; name2 = value2}</pre>
<p>If I wrote one of these using <em>write-object</em>, I got a nice list format with headers and could access the individual values via property syntax. Joy! Still, this isn&#8217;t <em>really</em> what I was looking for because I was really fishing for a way to output a PSObject.</p>
<h5>PSObjects</h5>
<p>You can create a PSObject using <em>New-Object</em>, but at first I couldn&#8217;t figure out how to let this object know it should have the properties I wanted. This is something you can use <em>Add-Member</em> for. You have to specify the type of member you are adding, and I believe the valid member types are listed in the <a href="http://msdn.microsoft.com/en-us/library/system.management.automation.psmembertypes(VS.85).aspx">PSMemberTypes</a> enumeration. In this case, I needed <em>NoteProperty</em> since there&#8217;s no base object:</p>
<pre class="code">$output = New-Object PSObject
$output | add-member NoteProperty -name Count -value $count
$output | add-member NoteProperty -name Average -value $average
$output | add-member NoteProperty -name AverageMinimum -value $averageMinimum
write-output $output</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.owenpellegrin.com/blog/powershell/writing-objects-from-powershell-scripts/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Expanding Wildcards in PowerShell</title>
		<link>http://www.owenpellegrin.com/blog/powershell/expanding-wildcards-in-powershell/</link>
		<comments>http://www.owenpellegrin.com/blog/powershell/expanding-wildcards-in-powershell/#comments</comments>
		<pubDate>Tue, 22 Jul 2008 21:11:59 +0000</pubDate>
		<dc:creator>Owen Pellegrin</dc:creator>
				<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://www.atmaweapon.org/blog/?p=29</guid>
		<description><![CDATA[Yesterday I thought I&#8217;d jump into the deep end of PowerShell and try to make a provider; this lets you treat some data store as a drive in PowerShell.&#160; It didn&#8217;t work out very well, mainly because I had no plan and just kind of hacked my way around it.&#160; I didn&#8217;t want to do [...]]]></description>
			<content:encoded><![CDATA[<p>Yesterday I thought I&#8217;d jump into the deep end of PowerShell and try to make a provider; this lets you treat some data store as a drive in PowerShell.&#160; It didn&#8217;t work out very well, mainly because I had no plan and just kind of hacked my way around it.&#160; I didn&#8217;t want to do an AccessDB provider like the MS one and came up with the idea of a provider that treated each line of a text file like an item.&#160; I kind of got overwhelmed with new information and decided to put it off for a bit.</p>
<p>So I switched to cmdlets today, since there&#8217;s a lot less planning involved in making some kind of cmdlet that does something.&#160; The one I&#8217;m making takes <em>Path</em> and <em>LineNumber</em> parameters, then tries to retrieve the line of text corresponding to <em>LineNumber</em> from the indicated files.&#160; I wanted to be fancy and accept wildcards in the <em>Path</em> parameter, and found that most people talking about wildcards are using a different approach to them than what I needed.</p>
<h5>What You&#8217;ll Find</h5>
<p>It seems like most people who talk about wildcards on the internet are excited about the <a href="http://msdn.microsoft.com/en-us/library/system.management.automation.wildcardpattern(VS.85).aspx">WildcardPattern</a> class.&#160; I can see why.&#160; Suppose I have a list of things I want to process and the user has given me a wildcard pattern to specify what items are important; if you don&#8217;t mind LINQ this is all it takes to prune your list:</p>
<pre style="overflow: auto; background: #efeff7;">var options = WildcardOptions.Compiled | WildcardOptions.IgnoreCase;
var pattern = new WildcardPattern(userPattern, options);

var matchedItems = from item in itemList
                   where pattern.IsMatch(item)
                   select item;</pre>
<p>That&#8217;s awesome; I don&#8217;t have to bother processing wildcards.&#160; However, it&#8217;s only useful if you have the list of items in the first place.&#160; In my cmdlet, the user can pass me any arbitrary path with wildcards and I need to fill in the blanks.&#160; The internet led me to believe this was the only wildcard processing in place, so I was looking at having to traverse the file system to make the list, then apply filtering.&#160; Yuck.</p>
<h5>What I Needed</h5>
<p>One of the things I like about PowerShell is I can tell MS really stands behind it and wants it to become the new command-line.&#160; The <a href="http://msdn.microsoft.com/en-us/library/ms714657(VS.85).aspx">Cmdlet Development Guidelines</a> are already up; compare this to other exciting technologies like WPF which get guidelines way after they&#8217;re released (I haven&#8217;t found any WPF ones, sadly).&#160; Anyway, I was looking over these guidelines and found what I needed under the section &quot;Support Windows PowerShell Paths&quot;.&#160; The <em>SessionState.Path</em> property is a <em>PathIntrinsics</em> instance that has several useful methods that do the wildcard expansion for me.&#160; For example, assuming I just happen to <em>know</em> the path is a PowerShell path, I can write this code:</p>
<pre style="overflow: auto; background: #efeff7;">ProviderInfo pInfo;
var resolvedPaths = SessionState.Path.GetResolvedProviderPathFromPSPath(FilePath, out pInfo);</pre>
<p>Now, <em>resolvedPaths </em>is a <em>Collection&lt;string&gt;</em> of every path name that matches the wildcards in the parameter.</p>
<p>One thing I&#8217;m curious about is what to do with this.&#160; My <em>Path</em> parameter is an array, as recommended by the design guidelines.&#160; My plan was to loop over all of the parameters, get the expanded paths, then get the indicated line numbers from each item.&#160; But I&#8217;m curious: is it wrong to do this expansion in <em>BeginProcessing</em> and replace my <em>Path</em> property with an array of fully-expanded items, then loop over that in <em>ProcessRecord</em>?&#160; It seems wrong to change the value of the user-provided parameters, but for some reason I don&#8217;t like the nested for loops that doing it all in <em>ProcessRecord</em> would require.&#160; I wonder if there&#8217;s a better way?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.owenpellegrin.com/blog/powershell/expanding-wildcards-in-powershell/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Working with Enumerations in PowerShell</title>
		<link>http://www.owenpellegrin.com/blog/tricks/working-with-enumerations-in-powershell/</link>
		<comments>http://www.owenpellegrin.com/blog/tricks/working-with-enumerations-in-powershell/#comments</comments>
		<pubDate>Mon, 21 Jul 2008 14:32:51 +0000</pubDate>
		<dc:creator>Owen Pellegrin</dc:creator>
				<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://www.atmaweapon.org/blog/?p=28</guid>
		<description><![CDATA[Two posts in one day should show you I&#8217;m excited about PowerShell. I wanted to update the script from my last post to find my My Documents folder so if I hop to Vista I won&#8217;t get an error, and I found it slightly difficult to figure out how to use Environment.GetFolderPath because I got [...]]]></description>
			<content:encoded><![CDATA[<p>Two posts in one day should show you I&#8217;m excited about PowerShell.</p>
<p>I wanted to update the script from <a href="http://www.atmaweapon.org/blog/?p=27">my last post</a> to find my My Documents folder so if I hop to Vista I won&#8217;t get an error, and I found it slightly difficult to figure out how to use <em>Environment.GetFolderPath</em> because I got a lot of errors trying to use the <em>Environment.SpecialFolder</em> enumeration.&#160; It turns out if you pass the string value for the enumeration value you want, you get basically what you want:</p>
<pre>$myDocs = $myDocs = [System.Environment]::GetFolderPath(&quot;MyDocuments&quot;)
Set-Location $myDocs
Set-Variable -name home -value $myDocs -force</pre>
<p>Apparently, <a href="http://weblogs.asp.net/soever/archive/2006/12/11/powershell-and-using-net-enum-types.aspx">you can also use flags enumerations</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.owenpellegrin.com/blog/tricks/working-with-enumerations-in-powershell/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
