<?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>PowerShell Station &#187; Scripts</title>
	<atom:link href="http://powershellstation.com/category/scripts/feed/" rel="self" type="application/rss+xml" />
	<link>http://powershellstation.com</link>
	<description>Mike&#039;s PowerShell Musings</description>
	<lastBuildDate>Thu, 05 Apr 2012 03:05:09 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>A Remoting Issue with PowerShell 3 Beta</title>
		<link>http://powershellstation.com/2012/04/05/a-remoting-issue-with-powershell-3-beta/</link>
		<comments>http://powershellstation.com/2012/04/05/a-remoting-issue-with-powershell-3-beta/#comments</comments>
		<pubDate>Thu, 05 Apr 2012 03:05:09 +0000</pubDate>
		<dc:creator>mike</dc:creator>
				<category><![CDATA[Scripts]]></category>
		<category><![CDATA[3.0 Beta]]></category>
		<category><![CDATA[PSRemoting]]></category>

		<guid isPermaLink="false">http://powershellstation.com/?p=411</guid>
		<description><![CDATA[I&#8217;ve been doing some thinking about PowerShell Remoting for a project at work and realized that I hadn&#8217;t ever set up remoting on my &#8220;home&#8221; laptop. I&#8217;m not in a domain, so remoting configuration is a bit different. In any case, I would be using the same machine as source and target of the remoting [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been doing some thinking about PowerShell Remoting for a project at work and realized that I hadn&#8217;t ever set up remoting on my &#8220;home&#8221; laptop.  I&#8217;m not in a domain, so remoting configuration is a bit different.  In any case, I would be using the same machine as source and target of the remoting call, so how could it go wrong?</p>
<p>First of all, VMWare had set up some network adapters and placed them in a public profile.  Enable-PSRemoting doesn&#8217;t like that.  It was an easy google (bing?) to fix and Enable-PSRemoting succeeded.</p>
<p>I then issued this:</p>
<pre class="brush:powershell">
invoke-command -scriptblock { get-process | select-object -first 10  } -computer  localhost
</pre>
<p>Imagine my surprise when the result was this:</p>
<pre>
Could not find file 'C:\Windows\System32\WindowsPowerShell\v1.0\Event.Format.ps1xml'.
    + CategoryInfo          : OpenError: (:) [], RemoteException
    + FullyQualifiedErrorId : PSSessionStateBroken
</pre>
<p>I searched the internet for this, but only found one hit that was close, and that was <a href="http://nuget.codeplex.com/workitem/2016" title="a bug report">a bug report</a> for <a href="http://nuget.codeplex.com/" title="nuget">nuget</a>.</p>
<p>It seems like the powershell engine that is running the remote payload is looking for a formatting file that doesn&#8217;t exist.  To work around this, I simply copied an existing Format.ps1xml file (I chose Registry.format.ps1xml because it was the smallest), removed the signature from it, and changed the name of the view (so it wouldn&#8217;t change any output).</p>
<p>It&#8217;s not a big bug, and it&#8217;s a beta so I&#8217;m not worried.  Just thought I&#8217;d share my workaround.</p>
<p>-Mike</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fpowershellstation.com%2F2012%2F04%2F05%2Fa-remoting-issue-with-powershell-3-beta%2F&amp;title=A%20Remoting%20Issue%20with%20PowerShell%203%20Beta" id="wpa2a_2"><img src="http://powershellstation.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://powershellstation.com/2012/04/05/a-remoting-issue-with-powershell-3-beta/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Speeding up Powershell Webcast by Dr. Tobias Weltner</title>
		<link>http://powershellstation.com/2012/03/13/speeding-up-powershell-webcast-by-dr-tobias-weltner/</link>
		<comments>http://powershellstation.com/2012/03/13/speeding-up-powershell-webcast-by-dr-tobias-weltner/#comments</comments>
		<pubDate>Tue, 13 Mar 2012 04:06:50 +0000</pubDate>
		<dc:creator>mike</dc:creator>
				<category><![CDATA[Scripts]]></category>

		<guid isPermaLink="false">http://powershellstation.com/?p=399</guid>
		<description><![CDATA[If you&#8217;ve done much looking around, you know that there&#8217;s an awful lot of great information about PowerShell available on the web. The community that has formed around this product is one of its strengths. You&#8217;re probably familiar with the name Tobias Weltner. His Master-PowerShell e-book has long been a resource that I&#8217;ve turned to [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;ve done much looking around, you know that there&#8217;s an awful lot of great information about PowerShell available on the web.  The community that has formed around this product is one of its strengths.  You&#8217;re probably familiar with the name Tobias Weltner.  His <a href="http://powershell.com/cs/blogs/ebook/" title="Master-PowerShell">Master-PowerShell</a> e-book has long been a resource that I&#8217;ve turned to for examples and explanations.  I recently watched a webcast that Dr. Weltner did as part of a series of webcasts at <a href="http://idera.com" title="Idera.com">idera.com</a>.  The title of the webcast is <a href="http://www.idera.com/Events/RegisterWC.aspx?EventID=297" title="Speeding up PowerShell: Multithreading">&#8220;Speeding up PowerShell: Multithreading&#8221;</a>.  When I got the announcement, I thought it was going to be about using the [System.Threading] namespace.  Boy, was I wrong.</p>
<p>The talk starts off with discussing times when it might make sense to avoid using the pipeline.  Once you see the material, it&#8217;s makes perfect sense.  He then moves to using PowerShell jobs to perform tasks, discussing the pros and cons of that approach.  Finally, he talks about using the Runspace class to run separate PowerShell instances.  It uses the classes, but still manages to be very readable, very approachable PowerShell.  He provides several examples in each section (including a function that executes a PowerShell scriptblock with a timeout, something I&#8217;ve never seen before).</p>
<p>All in all, this was easily the best webcast on PowerShell I&#8217;ve ever watched.  Unlike most Powershell videos I&#8217;ve seen, it wasn&#8217;t targeting a beginner, but someone who already knows the basics of scripting and wants to learn more.  The techniques he presents are, as I have said, very straightforward and explained very well.  I can already think of several examples of code that I&#8217;m probably going to be writing in the near future based on this presentation.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fpowershellstation.com%2F2012%2F03%2F13%2Fspeeding-up-powershell-webcast-by-dr-tobias-weltner%2F&amp;title=Speeding%20up%20Powershell%20Webcast%20by%20Dr.%20Tobias%20Weltner" id="wpa2a_4"><img src="http://powershellstation.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://powershellstation.com/2012/03/13/speeding-up-powershell-webcast-by-dr-tobias-weltner/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Importing Modules using -AsCustomObject</title>
		<link>http://powershellstation.com/2012/02/08/importing-modules-using-ascustomobject/</link>
		<comments>http://powershellstation.com/2012/02/08/importing-modules-using-ascustomobject/#comments</comments>
		<pubDate>Wed, 08 Feb 2012 04:46:26 +0000</pubDate>
		<dc:creator>mike</dc:creator>
				<category><![CDATA[Scripts]]></category>

		<guid isPermaLink="false">http://powershellstation.com/?p=379</guid>
		<description><![CDATA[I recently got thinking about the -AsCustomObject switch for the Import-Module cmdlet. I have seen it several times in discussions of implementing &#8220;classes&#8221; in PowerShell. Here&#8217;s a typical (i.e. trivial) example: #module adder.psm1 function add-numbers($x,$y){ return $x+$y } With that module, we can do the standard module stuff: PS> import-module adder PS> add-numbers 1 2 [...]]]></description>
			<content:encoded><![CDATA[<p>I recently got thinking about the -AsCustomObject switch for the Import-Module cmdlet. I have seen it several times in discussions of implementing &#8220;classes&#8221; in PowerShell. Here&#8217;s a typical (i.e. trivial) example:</p>
<pre class="brush:powershell">
#module adder.psm1
function add-numbers($x,$y){
   return $x+$y
}
</pre>
<p>With that module, we can do the standard module stuff:</p>
<pre class="brush:powershell">
PS> import-module adder
PS> add-numbers 1 2
3
</pre>
<p>Ok, that was way too basic. Here&#8217;s something a lot closer to the topic at hand:</p>
<pre class="brush:powershell">
PS> $adder=import-module adder -ascustomobject
PS> $adder | gm

   TypeName: System.Management.Automation.PSCustomObject

Name        MemberType   Definition
----        ----------   ----------
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()
GetType     Method       type GetType()
ToString    Method       string ToString()
add-numbers ScriptMethod System.Object add-numbers(); 

PS> $adder.add-numbers(1,2)
Unexpected token '-numbers' in expression or statement.
At line:1 char:11
PS>  $adder."add-numbers"( 1, 2)
3
</pre>
<p>There are a several interesting things to notice about this example. First of all, note that the add-numbers function has become a scriptmethod on the $adder object. As the help topic for import-module states, the members of the custom object are the (exported) members of the module. When we try to call the add-numbers method, we find that our decision to use the <em>noun-verb</em> naming convention has bitten us. To use the method, we need to enclose the offending method name in quotes (both single and double work fine). Note that since this is a method we need to use commas to separate the arguments to the function.</p>
<p>A second thing to note is since this is a method, not a function, we can&#8217;t skip arguments.</p>
<pre class="brush:powershell">PS> $adder.add-numbers(,2)</pre>
<p>Note that we could definitely do</p>
<pre class="brush:powershell">add-numbers -y 2</pre>
<p>if we had used a normal import-module. Granted that in this case there would be no need to.</p>
<p>What if we try to fix the quotation issue by including an alias (say, AddNumbers) to the module and exporting it?</p>
<pre class="brush:powershell">
function add-numbers($x,$y){
   return $x+$y
}
new-alias addNumbers add-numbers
export-modulemember -Function * -Variable * -alias *
</pre>
<p>Here&#8217;s what we find:</p>
<pre class="brush:powershell">
PS> $adder=import-module adder -ascustomobject -force
PS> $adder | gm

   TypeName: System.Management.Automation.PSCustomObject

Name        MemberType   Definition
----        ----------   ----------
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()
GetType     Method       type GetType()
ToString    Method       string ToString()
add-numbers ScriptMethod System.Object add-numbers(); 

PS> get-alias AddNumbers

Capability      Name                             ModuleName
----------      ----                             ----------
Script          addNumbers -> add-numbers        adder
</pre>
<p>Hey! Our alias is missing. Unfortunately, it got imported into the global scope (possibly hiding another function).  Note that I used the -force switch to make sure that we re-import it if it was already loaded.</p>
<p>When I first read about the -asCustomObject switch, I could see myself using this to import modules that had conflicting function names, and using the custom objects to call the methods in question.  However, consider a function with a large number of switches or parameters.  With an &#8220;-ascustomobject&#8221; object, you would need to specify all of the switches or parameters. Again, what about a function which used parametersets? As it turns out, scriptmethods don&#8217;t seem to use parametersets.  Here&#8217;s function to demonstrate:</p>
<pre class="brush:powershell">
function test-psets{
param([Parameter(ParameterSetName="Set1")]$x,
      [Parameter(ParameterSetName="Set2")]$y)
      switch ($PsCmdlet.ParameterSetName){
         "Set1" {write-host "we're using Set1"}
         "Set2"  {write-host "we're using Set2"}
         default {write-host "don't know what parameter set we're in"}
      }
      Write-host "we had better be using $($PsCmdlet.ParameterSetName)"
}
</pre>
<p>Calling that function on a custom object looks like this:</p>
<pre class="brush:powershell">
PS> $adder=import-module adder -ascustomobject -force
PS> $adder."test-psets"(1)   #should use pset 1, since we're only using the first parameter
don't know what parameter set we're in
we had better be using
PS> $adder."test-psets"(1,2)  #shouldn't be valid, since they're different parametersets
don't know what parameter set we're in
we had better be using
PS> #Sanity check to make sure the function works
PS> import-module adder
PS> test-psets -x 1
we're using Set1
we had better be using Set1

PS> test-psets -y 1
we're using Set2
we had better be using Set2

PS> test-psets -x 1 -y 2
test-psets : Parameter set cannot be resolved using the specified named parameters.
At line:1 char:1
+ test-psets -x 1 -y 2
+ ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [test-psets], ParameterBindingException
    + FullyQualifiedErrorId : AmbiguousParameterSet,test-psets
</pre>
<p>So it seems that functions that utilize parametersets are going to be a lot less useful with -AsCustomObject imports.</p>
<p>As I mentioned, there are several examples floating around concerning creating new objects (or classes, depending on your perspective) using modules and this option.  Given the drawbacks I&#8217;ve noted in this article, I think I&#8217;m going to stay away from that particular use case.</p>
<p>What do you think?  Did I miss something important?  Please let me know what your opinion is.</p>
<p>-Mike</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fpowershellstation.com%2F2012%2F02%2F08%2Fimporting-modules-using-ascustomobject%2F&amp;title=Importing%20Modules%20using%20-AsCustomObject" id="wpa2a_6"><img src="http://powershellstation.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://powershellstation.com/2012/02/08/importing-modules-using-ascustomobject/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Aggregation In PowerShell (and another pointless function)</title>
		<link>http://powershellstation.com/2011/12/14/aggregation-in-powershell-and-another-pointless-function/</link>
		<comments>http://powershellstation.com/2011/12/14/aggregation-in-powershell-and-another-pointless-function/#comments</comments>
		<pubDate>Wed, 14 Dec 2011 04:37:42 +0000</pubDate>
		<dc:creator>mike</dc:creator>
				<category><![CDATA[Discussion]]></category>
		<category><![CDATA[Scripts]]></category>

		<guid isPermaLink="false">http://powershellstation.com/?p=371</guid>
		<description><![CDATA[I&#8217;ve been doing a lot of thinking about &#8220;idiomatic PowerShell&#8221; since my last post and my thinking led me to an idea that I haven&#8217;t actually used, but seems like the kind of thing that people would do in PowerShell. If I were writing a script that needed to get a &#8220;bunch of things&#8221; from [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been doing a lot of thinking about &#8220;idiomatic PowerShell&#8221; since my <a title="PowerShell’s Problem with Return" href="http://powershellstation.com/2011/08/26/powershell%e2%80%99s-problem-with-return/">last post</a> and my thinking led me to an idea that I haven&#8217;t actually used, but seems like the kind of thing that people would do in PowerShell.</p>
<p>If I were writing a script that needed to get a &#8220;bunch of things&#8221; from somewhere (perhaps several different sources) and return all of them, I might be tempted to do something like this. Please forgive my PowerShell pseudocode:</p>
<pre class="brush: powershell">function get-stuff{
param($parm1 )
    $results=@()
    foreach ($source in $sources){
        $results += ($source | where { $_ -and "Some condition exists"  })
    }
    foreach ($source in $someothersources){
        $results += ($source | where { $_ -and "Some condition exists"  })
    }
 return $results
}</pre>
<p>I&#8217;ve used several permutations of that kind of code using arrays of some sort to collect the results as I go along and eventually return the collection from the function. I&#8217;m not sure that there&#8217;s anything wrong with doing it this way. That is, I&#8217;m not sure that you&#8217;re likely to have issues with doing it this way.</p>
<p>On the other hand, it&#8217;s more idiomatic (i.e more in the style of the PowerShell language) to do something like this (again, pardon the pseudocode):</p>
<pre class="brush: powershell">function get-stuff{
param($parm1 )
    foreach ($source in $sources){
        $source | where { $_ -and "Some condition exists"  }
    }
    foreach ($source in $someothersources){
        $source | where { $_ -and "Some condition exists"  }
    }

}</pre>
<p>All I&#8217;m doing here is sending the output of the inner statements (which are pipelines) to the output stream of the function. Note that there isn&#8217;t any need for anything to accumulate the results into.  Using the output stream makes this function work more like the built-in cmdlets in PowerShell as it won&#8217;t be blocking the pipeline.</p>
<p>The only thing that I have against this code is that it goes against rule #2 that I wrote last time about writing values to the output stream.  I said there that if you were going to write to the output stream, you should explicitly use <strong>write-output</strong>.  We could modify the code above to use <strong>write-output</strong>, but that would involve using parentheses (around the pipelines), messing up the flow of the code, and even blocking the pipeline while the expressions in the parentheses were collected (as an argument to write-output).  </p>
<p>That brings me to what I was saying about &#8220;another pointless function&#8221;.  About a year ago I wrote a <a href="http://powershellstation.com/2010/08/01/the-identity-function/" title="The Identity Function">post</a> about the identity function, which doesn&#8217;t really do anything except return the input.  It is a really useful function for creating lists and such, allowing you to skip on providing a bunch of punctuation.  It&#8217;s not a pointless function, but it&#8217;s not one that is getting much press, either.  I was thinking about how to make the &#8220;pipeline&#8221; version of the code work nicely and not make it ugly and thought of the following function.</p>
<pre class="brush: powershell">
function out-output{
    process{ $_ }
}
</pre>
<p>Like the identity function (or ql, as I&#8217;ve seen it referred to), out-output doesn&#8217;t do anything but emit values that are provided.  Out-output, however, gets its values from the pipeline rather than the argument list.  This function allows us to be explicit about our intent to use the output stream.</p>
<pre class="brush: powershell">function get-stuff{
param($parm1 )
    foreach ($source in $sources){
        $source | where { $_ -and "Some condition exists"  } | out-output
    }
    foreach ($source in $someothersources){
        $source | where { $_ -and "Some condition exists"  } | out-output
    }
}
</pre>
<p>I&#8217;m not sure if this is a good idea, and I know that it&#8217;s just adding a tiny bit of processing to the script.  My thought is that making the operation of the script explicit is worth it in the long run.</p>
<p>What do you think?</p>
<p>-mike</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fpowershellstation.com%2F2011%2F12%2F14%2Faggregation-in-powershell-and-another-pointless-function%2F&amp;title=Aggregation%20In%20PowerShell%20%28and%20another%20pointless%20function%29" id="wpa2a_8"><img src="http://powershellstation.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://powershellstation.com/2011/12/14/aggregation-in-powershell-and-another-pointless-function/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PowerShell’s Problem with Return</title>
		<link>http://powershellstation.com/2011/08/26/powershell%e2%80%99s-problem-with-return/</link>
		<comments>http://powershellstation.com/2011/08/26/powershell%e2%80%99s-problem-with-return/#comments</comments>
		<pubDate>Fri, 26 Aug 2011 22:29:36 +0000</pubDate>
		<dc:creator>mike</dc:creator>
				<category><![CDATA[Discussion]]></category>
		<category><![CDATA[Scripts]]></category>

		<guid isPermaLink="false">http://powershellstation.com/wordpress/?p=331</guid>
		<description><![CDATA[I think that PowerShell is a fairly readable language, once you’re used to its unique features. Naming functions (cmdlets) with an embedded hyphen, using -eq instead of the equals sign (and similarly for other operators) and not using commas to delimit parameters in a function call (but using them in a method call) are all [...]]]></description>
			<content:encoded><![CDATA[<p>I think that PowerShell is a fairly readable language, once you’re used to its unique features. Naming functions (cmdlets) with an embedded hyphen, using -eq instead of the equals sign (and similarly for other operators) and not using commas to delimit parameters in a function call (but using them in a method call) are all things that you get used to pretty quickly. There is one feature of PowerShell, however, that I don’t think will ever come naturally to me, and that’s how it handles return values from functions.</p>
<p>In most languages, if you see “return 1″ as the only return in a function, you can know that the function is going to the value 1 to the caller. In fact, I’m not sure I’ve ever seen a language that didn’t work that way. That is, until I found PowerShell. Generally speaking, the return statement works just as expected. In the absence of any statements writing to the output stream (with write-output) or “dropping” their values, “return 1″ will cause the caller to receive the value “1″. Using write-output is pretty obvious, and I’d recommend using it explicitly if you intend to add objects to the output stream (thereby including them in the eventual function value). Expressions that don’t capture their return values, however, are not quite so easy to spot.</p>
<p>For example, examine this code to add a parameter to an ADO.NET command object looks fine:</p>
<pre class="brush:powershell">$cmd.Parameters.AddWithValue('@demographics','$demoXML)</pre>
<p>This is a straightforward translation of one of the lines of code in the example code <a href="http://here/">here</a>.  The problem with the code is that AddWithValue not only adds a parameter, it also returns the parameter.  Since we didn’t assign it to a variable, cast it to [void] or pipe it to out-null, the output of this function (AddWithValue) gets added to the output of the function it’s in.</p>
<p>Several “add” functions in the .net framework follow this pattern, either returning the object that was added or the index of that object in the collection.  The DBConnection.Open method (inherited by SQLConnection, among others) returns the opened connection.  I’m sure that with time I could find more examples than I’d feel like sharing.</p>
<p>Another way that I’ve seen the output stream getting messed up is when a function uses strings to output information without using write-host.  For example, this function outputs “progress” information as it goes:</p>
<pre class="brush:powershell">
function get-filelength{
param($filename)
	"reading file"
	$len=0
	$file=get-content $filename
	foreach($line in $file){
	   "adding a line"
	   $len+=$line.length
	}
	return $len
}
</pre>
<p>I realize that this is not the best way to find the length of a file, but it works for the purpose of illustration. If you simply call the function (without assigning it to a variable), you’ll see a bunch of text, followed by the “value” of the function. The “returned value” of the function is clearly intended to be $len, but instead all of the text is included. The type of the function output is Object[], rather than a number.</p>
<p>There are some good reasons to use the output stream in a function (the next post will examine one such use), but it’s very easy to accidentally put something in the stream without intending to. When this happens, it often leads to unexpected results and long debugging sessions.</p>
<p>Here are my recommendations for avoiding this kind of error:</p>
<ol start="1">
<li>Use one of the “write” functions to provide text messages to the user (write-host, write-debug, write-verbose)</li>
<li>Use write-output if your intent is to add something to the output stream</li>
<li>Check msdn to see if the methods you use have output. If you’re looking at the C# version, methods that return void do not need to be “handled”. In the VB.NET version, they’ll be declared as Sub, rather than Function.</li>
<li>Be consistent with how you “handle” methods or functions whose values you want to discard. Options are to cast the result as [void] or pipe it to out-null</li>
<li>If you’re using write-output to put objects in the output stream, use return with no value (i.e., don’t return $val). Seeing a value returned explicitly implies that that is the only value returned.</li>
<li>If all else fails, use write-host to output the type of variables when debugging (or look at their values in the watch window if you’re using an IDE with a debugger).</li>
</ol>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fpowershellstation.com%2F2011%2F08%2F26%2Fpowershell%25e2%2580%2599s-problem-with-return%2F&amp;title=PowerShell%E2%80%99s%20Problem%20with%20Return" id="wpa2a_10"><img src="http://powershellstation.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://powershellstation.com/2011/08/26/powershell%e2%80%99s-problem-with-return/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Verifying Automation</title>
		<link>http://powershellstation.com/2011/01/06/verifying-automation/</link>
		<comments>http://powershellstation.com/2011/01/06/verifying-automation/#comments</comments>
		<pubDate>Fri, 07 Jan 2011 00:59:16 +0000</pubDate>
		<dc:creator>mike</dc:creator>
				<category><![CDATA[Discussion]]></category>
		<category><![CDATA[Scheduled Tasks]]></category>
		<category><![CDATA[Scripts]]></category>
		<category><![CDATA[Tools]]></category>

		<guid isPermaLink="false">http://powershellstation.com/?p=317</guid>
		<description><![CDATA[If you&#8217;re anything like me, you&#8217;ve been bitten by the PowerShell bug and are using it among other automation sources to make you life in IT much more enjoyable. If this is not the case&#8230;you need to get started!&#160; There&#8217;s no time like the present, and a PowerShell New Year&#8217;s resolution should be something to [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;re anything like me, you&#8217;ve been bitten by the PowerShell bug and are using it among other automation sources to make you life in IT much more enjoyable.  If this is not the case&#8230;you need to get started!&nbsp; There&#8217;s no time like the present, and a PowerShell New Year&#8217;s resolution should be something to consider.</p>
<p>For those of you that are with me in the PowerShell camp, I have something that I&#8217;d like to discuss.&nbsp; You probably have hundreds (dozens?) of scripts scheduled on multiple servers, possibly in multiple domains or geographical locations to perform things like these:</p>
<ul>
<li>Gather information about servers</li>
<li>Generate reports about application usage</li>
<li>Copy information from one place to another</li>
<li>Validate security setup</li>
<li>Start and Stop processes</li>
<li>Scan log files for error conditions</li>
<li>Lots of other things (you get the point)</li>
</ul>
<p>How do you know that the scripts that you have written carefully and scheduled are actually running successfully?&nbsp; At first, this seems like a silly question.&nbsp; When you deployed the script, surely you ran it once to make sure it worked.&nbsp; What could have gone wrong?</p>
<p>Here are some examples that come to mind:</p>
<ul>
<li>A policy was pushed which set the execution policy to Restricted</li>
<li>The credentials you scheduled the script with have been revoked</li>
<li>A file share that the scripts depend on is unavailable</li>
<li>Firewall rules change and now WMI queries aren&#8217;t working</li>
<li>The Task Scheduler service is stopped</li>
</ul>
<p>You can probably think of a lot more examples of things that would keep scripts from working, but you get the idea.&nbsp; I&#8217;ve given some thought to how to do this, but haven&#8217;t come to any real conclusions.&nbsp; Obviously, having your scripts log results is helpful, but only if you monitor the logs for success/failure.&nbsp; Also, if you have a script which is supposed to run every 10 minutes, it doesn&#8217;t help if you don&#8217;t get alerted when it only runs once in a day, even if&nbsp; it runs successfully.&nbsp; Also, if there is more than one person writing scripts, how do you make sure that everyone is using the same techniques to log progress?</p>
<p>Here are some of my thoughts:</p>
<ul>
<li>Use a &#8220;launcher&#8221; to run scripts (see below)</li>
<li>Keep a database of processes with an expected # of runs per day</li>
<li>Monitor matching start/end of scripts</li>
<li>Log all output streams (<a title="example" href="http://www.nivot.org/2009/08/19/PowerShell20AConfigurableAndFlexibleScriptLoggerModule.aspx">example</a>)</li>
</ul>
<p>The first item in the list (the launcher) has been something I&#8217;ve been considering because it&#8217;s not trivial to run a PowerShell script in a scheduled task.&nbsp; Even with the -file parameter which was added in PowerShell 2.0, it can involve a fairly long command-line.&nbsp; With the added difficulty of trying to capture output streams (most of which are not exposed to the command shell) it becomes a process that is almost hard to get right every time.&nbsp; Some features I&#8217;m planning for the launcher are:</p>
<ul>
<li>Load appropriate profiles</li>
<li>Log all output streams (with timestamps) to file or database</li>
<li>Log application start/end times</li>
<li>Email owner of script if there are unhandled exceptions</li>
</ul>
<p>I know this topic is not specific to PowerShell, but as Windows administrators get more used to scripting solutions to their automation problems with PowerShell (which I am confident that they are doing), it&#8217;s something that every organization will need to consider.&nbsp; I&#8217;ll try to follow up with some posts that have some actual code to address some of these points.</p>
<p>Mike</p>
<p>P.S.  I&#8217;m specifically not discussing &#8220;enterprise job scheduling&#8221; solutions like JAMS because of the high cost involved.  I&#8217;d like to see the community come up with something a little more budget-friendly.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fpowershellstation.com%2F2011%2F01%2F06%2Fverifying-automation%2F&amp;title=Verifying%20Automation" id="wpa2a_12"><img src="http://powershellstation.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://powershellstation.com/2011/01/06/verifying-automation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PowerShell and MongoDB</title>
		<link>http://powershellstation.com/2010/08/10/powershell-and-mongodb/</link>
		<comments>http://powershellstation.com/2010/08/10/powershell-and-mongodb/#comments</comments>
		<pubDate>Wed, 11 Aug 2010 02:23:31 +0000</pubDate>
		<dc:creator>mike</dc:creator>
				<category><![CDATA[Scripts]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://powershellstation.com/?p=293</guid>
		<description><![CDATA[I recently saw this link on using NoSQL with Windows.  Now, I&#8217;m a SQL Server DBA, so I haven&#8217;t really had any reason to use NoSQL.  I was curious about how easy it was going to be to set up and if I could get it working with PowerShell. I selected MongoDB from the list [...]]]></description>
			<content:encoded><![CDATA[<p>I recently saw <a title="this link" href="http://www.dotnetconvo.com/post/view/2010/8/9/nosql-on-the-microsoft-platform">this link</a> on using NoSQL with Windows.  Now, I&#8217;m a SQL Server DBA, so I haven&#8217;t really had any reason to use NoSQL.  I was curious about how easy it was going to be to set up and if I could get it working with PowerShell.</p>
<p>I selected MongoDB from the list because it looked more like something that would be used on smaller-scale projects.</p>
<p>I then googled &#8220;MongoDB PowerShell&#8221; and found <a title="this link" href="http://www.dougfinke.com/blog/index.php/2009/10/25/how-to-use-mongodb-from-powershell-and-f/">this link</a> from Doug Finke about using MongoDB with PowerShell (and F#, which is another &#8220;cool thing&#8221; I haven&#8217;t managed to find a need for).  Doug links to <a title="another article" href="http://odetocode.com/blogs/scott/archive/2009/10/13/experimenting-with-mongodb-from-c.aspx">another article</a> which explains setting up MongoDB and an open-source .Net driver for MongoDB called <a title="mongo-csharp" href="http://github.com/samus/mongodb-csharp">mongo-csharp</a>.  He then follows up with a straight-forward script showing simple usage of MongoDB.  It looks like an almost literal translation of the C# code from the article he references.  With those in hand, I thought it was going to be a slam dunk.</p>
<p>It was, but I had a few hurdles to get over before I could get it working.  There weren&#8217;t any problems with the code;  it was written about a year ago, so it was using PowerShell 1.0 and an older version of mongo-csharp.  I had to update the script in a couple of places to make it work.  I probably wouldn&#8217;t even write it up, given how minor the changes are, but I was somewhat disappointed with the number of hits I got for &#8220;MongoDB PowerShell&#8221;.</p>
<p>Here&#8217;s the updated script:</p>
<pre class="brush: powershell">add-type -Path .MongoDB.Driver.dll

$mongo=new-object mongodb.driver.mongo
$mongo.connect()
$db=$mongo.GetDataBase("movieReviews")
$movies=$db.GetCollection('Movies')

$movie=new-object Mongodb.driver.document
$movie['title']='Star Wars'
$movie['releaseDate']=get-date
$movies.Insert($movie)

$spec=new-object Mongodb.driver.document
$spec['title']='Star Wars'
$movies.FindOne($spec)
</pre>
<p>The two changes were</p>
<ol>
<li>added the parameter name (-path) to add-type, since the default param is looking for an assembly name, not a path to a DLL</li>
<li>changed $mongo.GetDB to $mongo.GetDatabase to reflect a change in the driver</li>
</ol>
<p>Worked fine.  Not sure how I&#8217;ll use this, but if I need to, I know I can from PowerShell.</p>
<p>-Mike</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fpowershellstation.com%2F2010%2F08%2F10%2Fpowershell-and-mongodb%2F&amp;title=PowerShell%20and%20MongoDB" id="wpa2a_14"><img src="http://powershellstation.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://powershellstation.com/2010/08/10/powershell-and-mongodb/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Checking a Field for NULL in PowerShell</title>
		<link>http://powershellstation.com/2010/04/09/checking-a-field-for-null-in-powershell/</link>
		<comments>http://powershellstation.com/2010/04/09/checking-a-field-for-null-in-powershell/#comments</comments>
		<pubDate>Sat, 10 Apr 2010 03:45:30 +0000</pubDate>
		<dc:creator>mike</dc:creator>
				<category><![CDATA[Scripts]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[NULL]]></category>
		<category><![CDATA[Script]]></category>

		<guid isPermaLink="false">http://powershellstation.com/2010/04/09/checking-a-field-for-null-in-powershell/</guid>
		<description><![CDATA[It’s been a long time (over 2 months) since I last posted.  I’ll try to get back into a rhythm of posting at least weekly.  Anyway, this is something that occurred to me at work when writing a script. I usually avoid nullable columns, but sometimes date fields make sense to be null (rather than [...]]]></description>
			<content:encoded><![CDATA[<p>It’s been a long time (over 2 months) since I last posted.  I’ll try to get back into a rhythm of posting at least weekly.  Anyway, this is something that occurred to me at work when writing a script.</p>
<p>I usually avoid nullable columns, but sometimes date fields make sense to be null (rather than use sentinel values like 1/1/1900).  In this case, I had a nullable date column and I needed to check in PowerShell whether the field was in fact null or not.  In SQL, I would have just used an IS NULL, or used the IsNull() function to replace the null value with something a little easier to deal with.  My first (feeble) attempt was to do this:</p>
<pre class="brush:powershell">if (!$_.completedDate){
# it’s null
}</pre>
<p>Unfortunately for me, that doesn’t work.  Next, I used this (which worked, but wasn’t very satisfactory either):</p>
<pre class="brush:powershell">if ($_.completedDate.ToString() -eq ''){
# it’s null
}</pre>
<p>Realizing that I was being stupid, I googled “PowerShell SQL NULL and after looking at several pages which didn’t really address the issue, I found <a href="http://blogs.technet.com/industry_insiders/pages/testing-for-database-null-values-from-powershell.aspx">this.</a> A little work to change it into a function, and voilà.</p>
<pre class="brush:powershell">function is-null($value){
  return  [System.DBNull]::Value.Equals($value)
}</pre>
<p>A few quick tests and this is what I wanted. Now, my code looks like this:</p>
<pre class="brush:powershell">if (is-null $_.completedDate){
# it’s null
}</pre>
<p>I find it hard to believe I haven’t written this function before (or seen it).</p>
<p>By the way…be watching the <a href="http://sqlpsx.codeplex.com">SQL PowerShell Extensions</a> project.  Chad released version 2.1, which includes SQL mode for the ISE (really nice).  I know he and several others are collaborating on an update which should be out sometime soon.</p>
<p>-Mike</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fpowershellstation.com%2F2010%2F04%2F09%2Fchecking-a-field-for-null-in-powershell%2F&amp;title=Checking%20a%20Field%20for%20NULL%20in%20PowerShell" id="wpa2a_16"><img src="http://powershellstation.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://powershellstation.com/2010/04/09/checking-a-field-for-null-in-powershell/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The PowerShell Bug That Wasn&#8217;t, and More Package Management</title>
		<link>http://powershellstation.com/2010/01/20/the-powershell-bug-that-wasnt-and-more-package-management/</link>
		<comments>http://powershellstation.com/2010/01/20/the-powershell-bug-that-wasnt-and-more-package-management/#comments</comments>
		<pubDate>Thu, 21 Jan 2010 05:04:26 +0000</pubDate>
		<dc:creator>mike</dc:creator>
				<category><![CDATA[Discussion]]></category>
		<category><![CDATA[Scripts]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[V2.0 Features]]></category>
		<category><![CDATA[Package]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Require]]></category>

		<guid isPermaLink="false">http://powershellstation.com/?p=255</guid>
		<description><![CDATA[Have you ever tracked down a bug, been confident that you had found the root of your problems, only to realize shortly afterwords that you missed it completely? What I posted yesterday as a bug in PowerShell (having to do with recursive functions, dot-sourcing, and parameters) seemed during my debugging session to clearly be a [...]]]></description>
			<content:encoded><![CDATA[<p>Have you ever tracked down a bug, been confident that you had found the root of your problems, only to realize shortly afterwords that you missed it completely?</p>
<p>What I posted yesterday as a bug in PowerShell (having to do with recursive functions, dot-sourcing, and parameters) seemed during my debugging session to clearly be a bug.  After all, I watched the parameter value change from b to a, didn&#8217;t I?  Sure did.  And in almost every language I&#8217;ve ever used, that would be a bug.  On the other hand, PowerShell is the only language that I know of that has dot-sourcing.  Here&#8217;s a much simpler code example which shows my faulty thinking:</p>
<pre class="brush: powershell">function f($x){
   if ($x -eq 1){
      write-host $x
      . f ($x+1)
      write-host $x
   }
}

f 1</pre>
<p>Here, we have a simple &#8220;recursive function&#8221; which uses dot-sourcing to call itself.  In my mind, how this would have worked is as follows:</p>
<ul>
<li>We call the function, passing 1 for $x</li>
<li>The if condition is true, so it prints 1 and calls the function, passing 2 for $x</li>
<li>In the inner call, the if condition is false, so nothing happens</li>
<li>We pop back to the calling frame, where $x is 1 and print it</li>
</ul>
<p>If it weren&#8217;t for that pesky dot operator, that would have been accurate.</p>
<p>The problem is, the dot operator changes the scoping of the inner call.  Here&#8217;s what the about_operators help topic, has to say about the dot sourcing operator:</p>
<pre>        Description: Runs a script so that the items in the script are part of the calling scope.</pre>
<p>Which is not a surprise&#8230;really.  The reason I was using the dot operator in my package management code was to make sure that functions defined in the scripts it was calling would be included in the existing scope, rather than their script scope.  The problem was one of nearsightedness.  I was so focused on the fact that the dot sourcing was making the functions part of the caller&#8217;s scope that I didn&#8217;t consider that variable declarations (including parameters) would also be in the caller&#8217;s scope.</p>
<p>So, the correct interpretation of the above script is:</p>
<ul>
<li>We call the function, passing 1 for $x</li>
<li>The if condition is true, so it prints 1 and calls the function, passing 2 for $x</li>
<li>The parameter is named $x, so $x in is set to 2 (overwriting the $x that was set to 1)</li>
<li>In the inner call, the if condition is false, so nothing happens</li>
<li>We pop back to the calling frame, where $x is 2 and print 2.</li>
</ul>
<p>The trick here is that the function f dot-sourced something that set $x to 2.  The fact that it was f is incidental.  It didn&#8217;t have to be.</p>
<p>Maybe this example will make it more clear:</p>
<pre class="brush:powershell">function f($x){
    write-host $x
    . g
    write-host $x
 }

function g{
   $x = "Hello, World!"
}
f 1</pre>
<p>If we were doing this without dot-sourcing, we would expect to see the number 1 printed out twice.  However, since we dot-sourced g, the assignment in the function body of g happens in the scope of f.  In other words, it&#8217;s as if the $x=&#8221;Hello, World!&#8221; were executed inside f.  Thus, the output of this script is 1, followed by &#8220;Hello, World!&#8221;.</p>
<p>So, it wasn&#8217;t a bug, it was just me not being thorough in applying my understanding of dot-sourcing.</p>
<p>Now, on with Package Management.<br />
First, to fix the problem caused by the parameter being overwritten (which it is, it&#8217;s just that it&#8217;s expected to be).  I hadn&#8217;t worked out a way to fix the problem before I went to bed last night, but as I was rolling this stuff around in my head (which is when I figured out that it wasn&#8217;t really a <em>bug</em>), I thought of a simple solution.  Since we can expect that sometimes the $filename parameter in the require (and reload) function will be overwritten by the a value in the dot-sourced script, we just need to make sure we&#8217;re done using it at that point.  So, I simply made the assignment to the dictionary before dot-sourcing.   Here&#8217;s the updated code:</p>
<pre class="brush: powershell">$global:loaded_scripts=@{pkg_utils='INITIAL'}

function require($filename){
	if (!$global:loaded_scripts[$filename]){
	   $global:loaded_scripts[$filename]=get-date
	   . scripts:$filename.ps1
	}
}
function reload($filename){
	$global:loaded_scripts[$filename]=get-date
	. scripts:$filename.ps1
}</pre>
<p>To add modules, we need to do a few extra things:</p>
<ul>
<li>We need to detect if we&#8217;re running in 2.0 or not</li>
<li>We need to see if there is a module with the given name</li>
<li>We need to see if the module is already loaded or not (in the case of require&#8230;it won&#8217;t matter for reload</li>
</ul>
<p>Fortunately, none of those are very difficult.  Here&#8217;s the updated code (including modules).  I even added some comments to make the flow more clear:</p>
<pre class="brush:powershell">
$global:loaded_scripts=@{pkg_utils='INITIAL'}

function require($filename){
    if ($global:loaded_scripts[$filename]){
          # this function has already loaded this (script or module)
          return
    }
    if ($psversiontable){
       # we're in 2.0
       if (get-module $filename -listavailable){
               #the module exists in the module path
         	   $global:loaded_scripts[$filename]=get-date
               import-module $filename
               return
       }
    }
    #it wasn't a module...so dot-source the script
    $global:loaded_scripts[$filename]=get-date
    . scripts:$filename.ps1

}
function reload($filename){
    if ($psversiontable){
        # we're in 2.0
        if (get-module $filename -listavailable){
           #the module exists in the module path
           $global:loaded_scripts[$filename]=get-date
           import-module $filename
           return
        }
    }
    # it wasn't a module...so dot-source the script.
  	$global:loaded_scripts[$filename]=get-date
	. scripts:$filename.ps1
}
</pre>
<p>That&#8217;s it for today.  Let me know what you think.</p>
<p>-Mike</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fpowershellstation.com%2F2010%2F01%2F20%2Fthe-powershell-bug-that-wasnt-and-more-package-management%2F&amp;title=The%20PowerShell%20Bug%20That%20Wasn%E2%80%99t%2C%20and%20More%20Package%20Management" id="wpa2a_18"><img src="http://powershellstation.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://powershellstation.com/2010/01/20/the-powershell-bug-that-wasnt-and-more-package-management/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Package Management and a PowerShell Bug</title>
		<link>http://powershellstation.com/2010/01/19/package-management-and-a-powershell-bug/</link>
		<comments>http://powershellstation.com/2010/01/19/package-management-and-a-powershell-bug/#comments</comments>
		<pubDate>Wed, 20 Jan 2010 05:41:58 +0000</pubDate>
		<dc:creator>mike</dc:creator>
				<category><![CDATA[Discussion]]></category>
		<category><![CDATA[Scripts]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[Package]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Require]]></category>

		<guid isPermaLink="false">http://powershellstation.com/?p=237</guid>
		<description><![CDATA[UPDATE: I have worked out how the behavior described at the end of this post is not a bug, but in fact just PowerShell doing what it&#8217;s told. Don&#8217;t have time to explain right now, but I&#8217;ll write something up later today. I also worked out how to &#8220;fix&#8221; the behavior. For a long time [...]]]></description>
			<content:encoded><![CDATA[<p><strong>UPDATE:  I have worked out how the behavior described at the end of this post is not a bug, but in fact just PowerShell doing what it&#8217;s told.  Don&#8217;t have time to explain right now, but I&#8217;ll write something up later today.  I also worked out how to &#8220;fix&#8221; the behavior.</strong></p>
<p>For a long time now, I&#8217;ve been dissatisfied with what I call &#8220;package management&#8221; in PowerShell.  Those of you who know me will be shocked that anything in PowerShell is less than perfect in my eyes, but this is one place that I feel let down.  Modules in 2.0 remedy the situation somewhat, but it still isn&#8217;t quite what I want or am used to in other languages.</p>
<p>Let me give an example.  In VB.NET, if you need to use the functions in an assembly, you put &#8220;Imports AssemblyName&#8221; at the top of your script.  In C#, you would have &#8220;Using AssemblyName&#8221;.  In Python, there would be &#8220;Import Something&#8221;.</p>
<p>In PowerShell 1.0, you had nothing.  In 2.0, you could create a module manifest which would specify either RequiredModules or ScriptsToProcess (or several other things to do upon loading the module).  The problems I see  with using the module manifest are:</p>
<ul>
<li>What if I&#8217;m not writing a module?  There&#8217;s no such thing as a &#8220;script manifest&#8221;</li>
<li>What if the script or module that is required performs some initialization that should only be done once per session?</li>
<li>What if the script or module that is required performs <em>expensive</em> initialization?</li>
</ul>
<p>Because of these reasons (and because I only started using 2.0 when it went RTM) I wrote a couple of quick functions to do what I thought made sense.</p>
<pre class="brush: powershell">
$global:loaded_scripts=@{pkg_utils='INITIAL'}

function require($filename){
	if (!$global:loaded_scripts[$filename]){
	   . scripts:$filename.ps1
	   $global:loaded_scripts[$filename]=get-date
	}
}
function reload($filename){
	. scripts:$filename.ps1
	$global:loaded_scripts[$filename]=get-date
}
</pre>
<p>To use these you need to create a psdrive called scripts: with code like this (probably in your profile):</p>
<pre class="brush:powershell">New-PSdrive -name scripts -PSprovider filesystem -root PathToYourLibraries | Out-Null</pre>
<p>Then, also in your profile, you&#8217;ll want to dot-source the file you put these functions in (for example, package_tools.ps1):</p>
<pre class="brush: powershell">. scripts:package_tools.ps1</pre>
<p>Once you have those set up, you can dot-source the <strong>require</strong> function to make sure that a script has been loaded as such:</p>
<pre class="brush:powershell">. require somelibrary</pre>
<p>I have the functions I use divided by &#8220;subject&#8221; into several library scripts, and make sure that at the top of each script, I use &#8220;. require&#8221; to ensure that any prerequisites are already loaded.</p>
<p>Now for the PowerShell bug (which took me a long time to track down).<br />
Create 2 files, a.ps1 and b.ps1 in your scripts: directory.</p>
<pre class="brush:powershell">
# a.ps1
write-host "this is script a"
</pre>
<pre class="brush: powershell">
#b.ps1
write-host "this is script b"
write-host "this script loads a"
. require a
</pre>
<p>After dot-sourcing package_tools, run the following commands:</p>
<pre class="brush: powershell">
. require b
</pre>
<p>You should get output that looks something like this:</p>
<pre>
this is script b
this script loads a
this is script a
</pre>
<p>Everything looks good until you inspect the $global:loaded_scripts variable:</p>
<pre>
ps> $loaded_scripts

Name                           Value
----                           -----
a                              1/19/2010 11:23:09 PM
package_tools                  INITIAL
</pre>
<p>Although b.ps1 was indeed dot-sourced (you can see the output), and the only code-path through the  require function that would dot-source it would also add an entry to $loaded_scripts, there is no such entry.  The problem is that when b.ps1 called the require function (to load a.ps1), the $filename variable in the calling context (where it should have been &#8220;b&#8221;) was overwritten by the call with &#8220;a&#8221; as a parameter.  Walking through the code in a debugger confirms the problem.</p>
<p>Have you ever seen problems with recursion and dot-sourcing in PowerShell?  Can you see any way around the problem I&#8217;ve described?  For instance, saving the $filename in a variable and restoring it after the dot-source call (line 5 above) doesn&#8217;t help, because the same code-path is followed in the recursive call, and that variable is overwritten as well.</p>
<p>Even with this bug, I find the require function (and reload, which I didn&#8217;t discuss, but always loads the script in question) to be very helpful.  I also have extended them to include importing modules, if they exist.  I&#8217;ll discuss them in my next post, coming soon.</p>
<p>-Mike</p>
<p>P.S.  <a href="http://stackoverflow.com/questions/279974/importing-libraries-in-powershell">Here</a>&#8216;s a question I posted to StackOverflow.com about these functions back in November of 2008.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fpowershellstation.com%2F2010%2F01%2F19%2Fpackage-management-and-a-powershell-bug%2F&amp;title=Package%20Management%20and%20a%20PowerShell%20Bug" id="wpa2a_20"><img src="http://powershellstation.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://powershellstation.com/2010/01/19/package-management-and-a-powershell-bug/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
<!-- This Quick Cache file was built for (  powershellstation.com/category/scripts/feed/ ) in 0.27846 seconds, on May 20th, 2012 at 1:21 am UTC. -->
<!-- This Quick Cache file will automatically expire ( and be re-built automatically ) on May 21st, 2012 at 1:21 am UTC -->
