<?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>Elegant Code &#187; PowerShell</title>
	<atom:link href="http://elegantcode.com/category/microsoft/powershell/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Silverlight Profiling PowerShell helper.</title>
		<link>http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=silverlight-profiling-powershell-helper</link>
		<comments>http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/#comments</comments>
		<pubDate>Sat, 15 May 2010 16:47:22 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/</guid>
		<description><![CDATA[I was playing around with some Silverlight profiling the other night to see if I could find any obvious issues with my open source project StatLight and wound up writing a little script in PowerShell I hoped someone might find helpful. But I didn’t know you could profile a Silverlight app. I didn’t until I [...]]]></description>
			<content:encoded><![CDATA[<p>I was playing around with some Silverlight profiling the other night to see if I could find any obvious issues with my open source project <a href="http://statlight.net" target="_blank">StatLight</a> and wound up writing a little script in PowerShell I hoped someone might find helpful.</p>  <h4>But I didn’t know you could profile a Silverlight app.</h4>  <p>I didn’t until I started doing some digging online. Now, the Silverlight profiling story (at least from what I’ve seen/tried) is not near the easy of say <a href="http://www.red-gate.com/products/ants_performance_profiler/index.htm">Redgate ANTS Performance Profiler</a>. However, it’s do-able. (And with this helper script – hopefully a little simpler?)</p>  <h4>How can I profile a Silverlight Application?</h4>  <p>I would recommend you read the following blog, which explains one way of doing it very well.</p>  <p><a title="http://blogs.msdn.com/profiler/archive/2010/04/26/vs2010-silverlight-4-profiling.aspx" href="http://blogs.msdn.com/profiler/archive/2010/04/26/vs2010-silverlight-4-profiling.aspx">http://blogs.msdn.com/profiler/archive/2010/04/26/vs2010-silverlight-4-profiling.aspx</a></p>  <h4>So… what’s this script for?</h4>  <p>If you read the blog above, or have done this before, then you probably noticed that there was quite a series of commands you had to execute before you could wind up with a performance report. </p>  <p>I threw together a quick little PowerShell script in an attempt to automate smooth out the process.</p>  <h4>Hot do I use it?</h4>  <ol>   <li>Download the script &amp; save it somewhere. <a href="http://github.com/staxmanade/Scripts/blob/master/SilverlightProfiler.ps1"><strong>http://github.com/staxmanade/Scripts/blob/master/SilverlightProfiler.ps1</strong></a> </li>    <li>Open the PowerShell console. cd to the directory your xap/assemblies are stored.      <br />(EX: {myProject}\Bin\Debug\ ) </li>    <li>Execute:      <br />{pathToScript}\SilverlightProfiler.ps1 -urlPath &quot;{myProject}\Bin\Debug\TestPage.html&quot; </li>    <li>When your done profiling press enter to signal that your done.      <p></p> Once complete, it will print the location your profiling report was saved. You can then open it with Visual Studio.</li> </ol>  <h5>Couple of disclaimers.</h5>  <ul>   <li>Some paths are hard-coded to my x86 machine. </li>    <li>I had troubles running the built in visual studio .bat files (from powershell) that are supposed to set the environment variables. So I extracted out what vars I could find to make it work. </li>    <li>I’m not a profiling expert – just hacked this together to get it to work for me.</li> </ul>  <p>I hope this is useful, and if you know of a better way, I’m always interested in hearing your feedback.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Powershell: Load assembly without locking file.</title>
		<link>http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-load-assembly-without-locking-file</link>
		<comments>http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/#comments</comments>
		<pubDate>Wed, 23 Dec 2009 05:40:23 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/</guid>
		<description><![CDATA[I have a set of PowerShell build scripts and ran into a case where I needed to load an assembly (to get the assembly’s version) and still (at a later time) work with the assembly file on disk. A typical way to load an assembly within PowerShell is to use the Assembly.LoadFrom(filePath) # Powershell [System.Reflection.Assembly]::LoadFrom($assemblyPath) [...]]]></description>
			<content:encoded><![CDATA[<p>I have a set of PowerShell build scripts and ran into a case where I needed to load an assembly (to get the assembly’s version) and still (at a later time) work with the assembly file on disk.</p>  <p>A typical way to load an assembly within PowerShell is to use the Assembly.LoadFrom(filePath)</p>  <blockquote>   <p># Powershell</p>    <p>[System.Reflection.Assembly]::LoadFrom($assemblyPath)</p> </blockquote>  <p><a href="http://elegantcode.com/wp-content/uploads/2009/12/image9.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://elegantcode.com/wp-content/uploads/2009/12/image_thumb9.png" width="690" height="391" /></a> </p>  <p>Except the problem with this (in my case) was it would <strong>lock the file for the lifespan of the PowerShell console instance</strong>. I didn’t want to have to close and re-open the PowerShell console every time I need to run a build so there had to be a work-around for this.</p>  <p>After searching the web for a solution, I couldn’t find anything that was “easy” and worth the effort to get it to work.</p>  <blockquote>   <p>EX: One solution was to create a new AppDomain, do the necessary work and the close the AppDomain which would release the lock on the file.</p>    <p>I’ve never done this myself, and even thought there is example code out there to get this accomplished, it just seemed over the top for what I was trying to do, and back to my previous criteria it wasn’t “worth the effort to get it to work”</p> </blockquote>  <p>Then I remembered in a previous life I used an overload that took an array of bytes to load the an assembly.</p>  <blockquote>   <p>[System.Reflection.Assembly]::Load($assemblyBytes)</p> </blockquote>  <p>After spiking it in PowerShell with the below test. I was quite happy with the solution, so I thought I’d throw it out there.</p>  <p>Just stream the assembly from disk into a byte array manually, and call assembly load from there.</p>  <p>Here’s my test case which shows that the file is not locked after it was loaded into the PowerShell runtime</p>  <pre>$file = &quot;.\Moq.dll&quot;
$tempFileName = &quot;.\Moq-Renamed.dll&quot;

$fileStream = ([System.IO.FileInfo] (Get-Item $file)).OpenRead();
$assemblyBytes = new-object byte[] $fileStream.Length
$fileStream.Read($assemblyBytes, 0, $fileStream.Length);
$fileStream.Close();

$assemblyLoaded = [System.Reflection.Assembly]::Load($assemblyBytes);

# notice that we can move the file on disk after 
# it's loaded into the powershell runtime
Move-Item $file $tempFileName
Move-Item $tempFileName $file 

# and display the assembly information to show we still have it in memory
echo $assemblyLoaded</pre>

<p>After that test passed, and the main reason I wanted to do this, I wrote the “get-assembly-version” PowerShell function.</p>

<pre><strike>function get-assembly-version() {
    param([string] $file)
    
    # load the assembly bytes quickly - as to not lock the file for too long
    $fileStream = ([System.IO.FileInfo] (Get-Item $file)).OpenRead()
    $assemblyBytes = new-object byte[] $fileStream.Length
    $fileStream.Read($assemblyBytes, 0, $fileStream.Length) | Out-Null #out null this because this function should only return the version &amp; this call was outputting some garbage number
    $fileStream.Close()
    
    # return the version of the assembly
    [System.Reflection.Assembly]::Load($assemblyBytes).GetName().Version;
}

$version = get-assembly-version(&quot;.\Moq.dll&quot;)

echo &quot;Loaded v$($version.Major).$($version.Minor).$($version.Build).$($version.Revision) version of $file&quot;</strike></pre>
Hope this helps someone out there! 

<p></p>

<p>&#160;</p>

<p><strong>UPDATE:</strong></p>

<p><a href="http://achuebrigens.wordpress.com">Martin</a> commented below on a much better solution to the assembly version info problem. Amazing how complicated we can make things if we don’t know the path.</p>

<pre>
function get-assembly-version() {
    param([string] $file)
    
    $version = [System.Reflection.AssemblyName]::GetAssemblyName($file).Version;
    
    #format the version and output it...
    $version
}</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Integration Test Brought to you by Powershell &amp; NUnit &#8211; with a Little Specification Syntax for Flavoring</title>
		<link>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring</link>
		<comments>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/#comments</comments>
		<pubDate>Mon, 26 Oct 2009 05:00:40 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/</guid>
		<description><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about Fluent Specification Extensions in a past blog. Recently I wanted to execute a PowerShell script [...]]]></description>
			<content:encoded><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about <a href="http://staxmanade.blogspot.com/2009/02/fluent-specification-extensions.html">Fluent Specification Extensions</a> in a past blog.

Recently I wanted to execute a PowerShell script to do some automated <a href="http://en.wikipedia.org/wiki/Functional_testing">functional testing</a>. I wanted to execute an application and apply some assertions on the output of the software(basically running a console app, parse the xml output and assert on values in the output).
<blockquote>FYI: I’m very new to PowerShell, so any suggestions on how I implemented the below are welcome…</blockquote>
I’ve seen a couple examples of writing test assertions in PowerShell out there. One example is <a href="http://www.psunit.org/">PSUnit</a>; however, this seemed a little heavy for my needs and not quite the syntactic sugar I was looking for.

Besides the syntax flavor I was desiring, another thing I wanted to do was leverage the power of NUnit.Framework’s assertion capabilities. I like the error messages generated when strings and other objects fail the assertion.
<h5>Examples of end result ShouldLookLike()…</h5>
$true.ShouldBeTrue()
$false.ShouldBeFalse()
"a".ShouldEqual("a")
"a".ShouldNotEqual("b")
<h5><strong>Step 1</strong>: Figure out how to write a C# style <a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx">extension method</a> in PowerShell.</h5>
<blockquote>I found a great blog post describing how to extend any PowerShell object to add extension methods.

<a href="http://bartdesmet.net/blogs/bart/archive/2007/09/06/extension-methods-in-windows-powershell.aspx">Extension Methods in Windows PowerShell</a></blockquote>
In short, to extend types in PowerShell leveraging the <a href="http://msdn.microsoft.com/en-us/library/ms714419(VS.85).aspx">Extended Type System</a>, you need to define them in an xml file and import the method definitions into the PowerShell runtime instance.

Below is PowerShell XML definition for my NUnit Specification Extensions.
<pre class="brush: xml;">&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;Types&gt;
    &lt;Type&gt;
        &lt;Name&gt;System.Object&lt;/Name&gt;
        &lt;Members&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeFalse&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsFalse($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeTrue&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsTrue($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldNotEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreNotEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
        &lt;/Members&gt;
    &lt;/Type&gt;
&lt;/Types&gt;</pre>
<h4></h4>
Take the above XML and save it to a file…
<blockquote>NOTE: the file HAS to be saved with the extension <strong>.ps1xml</strong>

Ex: NunitSpecificationPowerShellExtensions<strong>.ps1xml</strong></blockquote>
<h4></h4>
<h5>Step 2: Load the extended type definition into the PowerShell runtime.</h5>
Once you’ve saved the XML extended types to a file, you need to load it into the PowerShell runtime by executing the command below.
<blockquote>
Update-TypeData -PrependPath NunitSpecificationPowerShellExtensions.ps1xml</blockquote>
Before executing the above statement…Let’s quickly look at a System.String’s members and properties – just to show you what the extension methods look like when applied inside of the runtime.<a href="http://elegantcode.com/wp-content/uploads/2009/10/image3.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb2.png" border="0" alt="image" width="586" height="479" /></a>

After executing the Update-TypeData command you’ll notice there are a number of “ScriptMethod” MemberTypes added to the object.

<a href="http://elegantcode.com/wp-content/uploads/2009/10/image4.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb3.png" border="0" alt="image" width="600" height="580" /></a>

Now if you try to execute one of those newly added extension methods, you may get the following error…

PS C:\&gt; $testVar.<strong>ShouldEqual</strong>("hello world")

Exception calling "ShouldEqual" with "1" argument(s): "<strong>Unable to find type [NUnit.Framework.Assert]: make sure that the

assembly containing this type is loaded.</strong>"

At line:1 char:21

+ $testVar.ShouldEqual &lt;&lt;&lt;&lt; ("hello world")

+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

+ FullyQualifiedErrorId : ScriptMethodRuntimeException

This is because we need to load the NUnit.Framework assembly into the runtime before we can leverage the extension methods.
<blockquote>[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null</blockquote>
Now that the extension methods have been defined and loaded into the runtime, NUnit.Framework is loaded, we can now use the methods on any object that inherits from System.Object (which, as far as I know, is everything in PowerShell).

And now, everything you need in one script (if you have the xml extended type file saved somewhere…)
<pre>#
# Update-TypeData -prependPath C:\Code\NunitSpecificationPowerShellExtensions.ps1xml
#

[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null

$true.ShouldBeTrue()

$false.ShouldBeFalse()

"a".ShouldEqual("a")

"a".ShouldNotEqual("b")</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>PowerShell Management Library for Hyper-V</title>
		<link>http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-management-library-for-hyper-v</link>
		<comments>http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/#comments</comments>
		<pubDate>Wed, 25 Mar 2009 21:46:16 +0000</pubDate>
		<dc:creator>Alex Mueller</dc:creator>
				<category><![CDATA[Hyper-V]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Tools and Utilities]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/</guid>
		<description><![CDATA[I am always looking for tools to allow me to do more by doing less. Administering Hyper-V with PowerShell can be tedious. James O’Neill’s PowerShell Management Library for Hyper-V is a great tool to improve automation of Hyper-V management using PowerShell. As a tester, I am constantly creating new environments, installing our product, taking snapshots, [...]]]></description>
			<content:encoded><![CDATA[<p>I am always looking for tools to allow me to do more by doing less. Administering Hyper-V with PowerShell can be tedious. James O’Neill’s <a href="http://pshyperv.codeplex.com/" target="_blank">PowerShell Management Library for Hyper-V</a> is a great tool to improve automation of Hyper-V management using PowerShell.</p>  <p>As a tester, I am constantly creating new environments, installing our product, taking snapshots, ect. Doing this by hand is a waste of time in my opinion. Doing this with a script makes life easier and frees up my time. </p>  <p>Typically, I prefer to create is to create one VM and to have other VMs inherit from that base image. My second VM (the first child to inherit from the base), I will install daily builds of our product. I will then create a third child, which I use a sandbox. I can easily delete it and recreate as needed without having to install our product over again. I have not consistently found success with using snapshots, so I prefer to use differencing disks. The examples below use differencing disks. </p>  <p>This first code block shows how I am using the PowerShell management library to simply the creation of a base VM. There is nothing magic about it. It’s pretty strait-forward. I create a VM, give it a name, set the CPU count, memory size, network adapters, hard drive, and DVD drive.</p>  <pre class="code"><span style="color: purple">$server </span><span style="color: red">= </span><span style="color: maroon">&quot;my-dev-server&quot;
</span><span style="color: purple">$vmName </span><span style="color: red">= </span><span style="color: maroon">&quot;TestParentVM&quot;
</span><span style="color: purple">$vmVirtualSwitch </span><span style="color: red">= </span><span style="color: maroon">&quot;My Virtual Network&quot;

</span><span style="color: green"># create a new virtual machine
</span><span style="color: purple">$vm </span><span style="color: red">= </span><span style="color: black">New-VM </span><span style="color: purple">$vmName </span><span style="color: black">-server </span><span style="color: purple">$server

</span><span style="color: green"># set cpu count
</span><span style="color: black">Set-VMCPUCount </span><span style="color: purple">$vm </span><span style="color: black">2 -server </span><span style="color: purple">$server

</span><span style="color: green"># set memory size
</span><span style="color: black">Set-VMMemory </span><span style="color: purple">$vm </span><span style="color: black">2 -memory 4GB -server </span><span style="color: purple">$server

</span><span style="color: green"># add a legacy network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch </span><span style="color: black">-legacy

</span><span style="color: green"># add a default VMBus (non-legacy) network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch

</span><span style="color: green"># add the hard drive to the VM
</span><span style="color: black">Add-VMNewHardDisk –vm </span><span style="color: purple">$vm </span><span style="color: black">-controllerID 0 -lun 0 -vhdpath </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmName.vhd&quot; </span><span style="color: black">-size 20GB

</span><span style="color: green"># add the DVD with bootup ISO
</span><span style="color: black">Add-VMDRIVE –vm </span><span style="color: purple">$vm </span><span style="color: black">1 1 -server </span><span style="color: purple">$server </span><span style="color: black">-DVD 

</span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;Operation complete.&quot;</span></pre>
<a href="http://11011.net/software/vspaste"></a>

<p>The next code block will create a differencing disk pointing to the parent created in the previous example. I create the usual, VM, CPU count, ect. What makes this a differencing disk is how the VHD is created by specifying the parent. I do some cleanup in this routine by deleting any previously created VMs or VHDs, and I loop through the creation a failure preventative. </p>

<pre class="code"><span style="color: purple">$server </span><span style="color: red">= </span><span style="color: maroon">&quot;my-dev-server&quot;
</span><span style="color: purple">$vmName </span><span style="color: red">= </span><span style="color: maroon">&quot;TestChildVM&quot;
</span><span style="color: purple">$vmParent </span><span style="color: red">= </span><span style="color: maroon">&quot;TestParentVM&quot;
</span><span style="color: purple">$vmVirtualSwitch </span><span style="color: red">= </span><span style="color: maroon">&quot;My Virtual Network&quot;

</span><span style="color: blue">#region </span><span style="color: black">functions - feel free to move to a separate file

</span><span style="color: blue">Function </span><span style="color: #5f9ea0">DeleteVhd
</span><span style="color: black">{
    </span><span style="color: blue">Param </span><span style="color: black">(</span><span style="color: purple">$pathToVhd</span><span style="color: black">)
    </span><span style="color: green"># delete the disk that was added if it exists
    </span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: #5f9ea0">test-path -path </span><span style="color: purple">$pathToVhd</span><span style="color: black">)
    {
        </span><span style="color: #5f9ea0">Remove-Item -Path </span><span style="color: purple">$pathToVhd </span><span style="color: #5f9ea0">-Force
    </span><span style="color: black">}
}

</span><span style="color: blue">#endregion

</span><span style="color: green"># delete the VHD if it already exists
</span><span style="color: #5f9ea0">DeleteVhd </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmName.vhd&quot;

</span><span style="color: green"># delete the VM if it already exists
</span><span style="color: black">Remove-VM -vm </span><span style="color: purple">$vmName </span><span style="color: black">-server </span><span style="color: purple">$server

</span><span style="color: green"># create a new virtual machine
</span><span style="color: purple">$vm </span><span style="color: red">= </span><span style="color: black">New-VM </span><span style="color: purple">$vmName </span><span style="color: black">-server </span><span style="color: purple">$server

</span><span style="color: green"># get the vm
</span><span style="color: purple">$vm </span><span style="color: red">= </span><span style="color: black">Get-VM </span><span style="color: purple">$vmName

</span><span style="color: green"># set cpu count
</span><span style="color: black">Set-VMCPUCount </span><span style="color: purple">$vm </span><span style="color: black">2 -server </span><span style="color: purple">$server

</span><span style="color: green"># set memory size
</span><span style="color: black">Set-VMMemory </span><span style="color: purple">$vm </span><span style="color: black">2 -memory 4GB -server </span><span style="color: purple">$server

</span><span style="color: green"># get VM Nics available
</span><span style="color: purple">$vmNics </span><span style="color: red">= </span><span style="color: black">Get-VMNic -server </span><span style="color: purple">$server </span><span style="color: black">-vmbus -legacy
</span><span style="color: purple">$vmNicSwitchList </span><span style="color: red">= </span><span style="color: #5f9ea0">New-Object </span><span style="color: maroon">System.Collections.ArrayList

</span><span style="color: green"># get VM Nic Switch available for each VM Nic and add it to our list
</span><span style="color: blue">foreach </span><span style="color: black">(</span><span style="color: purple">$vmNic </span><span style="color: blue">in </span><span style="color: purple">$vmNics</span><span style="color: black">)
{
    </span><span style="color: purple">$vmSwitchElementName </span><span style="color: red">= </span><span style="color: black">(Get-VMNicSwitch </span><span style="color: purple">$vmNic</span><span style="color: black">).ElementName
    </span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">.Contains(</span><span style="color: purple">$vmSwitchElementName</span><span style="color: black">) </span><span style="color: red">-ne </span><span style="color: blue">$true</span><span style="color: black">)
    {
        </span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">.Add(</span><span style="color: purple">$vmSwitchElementName</span><span style="color: black">)
    }
}

</span><span style="color: green"># Use the first available VM Nic Switch - this assumes 
# I do not create more than on per each environment.
</span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">.Count </span><span style="color: red">-gt </span><span style="color: black">0)
{
    </span><span style="color: purple">$vmVirtualSwitch </span><span style="color: red">= </span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">[0]
}

</span><span style="color: green"># add a legacy network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch </span><span style="color: black">-legacy

</span><span style="color: green"># add a default VMBus (non-legacy) network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch

</span><span style="color: green"># add the hard drive to the VM
</span><span style="color: purple">$parent </span><span style="color: red">= </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmParent.vhd&quot;
</span><span style="color: purple">$vhdPath </span><span style="color: red">= </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmName.vhd&quot;
</span><span style="color: black">Add-VMNewHardDisk –vm </span><span style="color: purple">$vm </span><span style="color: black">-controllerID 0 -lun 0 -vhdpath </span><span style="color: purple">$vhdPath </span><span style="color: black">-parent </span><span style="color: purple">$parent

</span><span style="color: green"># get the VM to see if a disk is attached to it, if it is not, then it failed
</span><span style="color: purple">$disks </span><span style="color: red">= </span><span style="color: black">Get-VMDisk -vm </span><span style="color: purple">$vm
$count </span><span style="color: red">= </span><span style="color: black">1

</span><span style="color: green"># if the disk was not successfully added, try and add it again
</span><span style="color: blue">while </span><span style="color: black">(</span><span style="color: purple">$disks </span><span style="color: red">-eq </span><span style="color: purple">$null </span><span style="color: red">-and </span><span style="color: purple">$count </span><span style="color: red">-le </span><span style="color: black">5)
{
    </span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;RETRY $count - The disk was not properly added. Attempting to retry.&quot;
    
    </span><span style="color: green"># delete the disk that was added
    </span><span style="color: #5f9ea0">DeleteVhd </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmName.vhd&quot;
    
    </span><span style="color: black">Add-VMNewHardDisk –vm </span><span style="color: purple">$vm </span><span style="color: black">-controllerID 0 -lun 0 -vhdpath </span><span style="color: purple">$vhdPath </span><span style="color: black">-parent </span><span style="color: purple">$parent
    
    $disks </span><span style="color: red">= </span><span style="color: black">Get-VMDisk -vm </span><span style="color: purple">$vm
    $count</span><span style="color: red">++
</span><span style="color: black">}

</span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: purple">$disks </span><span style="color: red">-eq </span><span style="color: purple">$null</span><span style="color: black">)
{
    </span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;Operation failed to create this virtual machine. Contact an admin.&quot;
</span><span style="color: black">}
</span><span style="color: blue">else
</span><span style="color: black">{
    </span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;Operation completed successfully. Attempting to start the VM.&quot;
    </span><span style="color: black">Start-VM -vm </span><span style="color: purple">$vm </span><span style="color: black">-wait
}</span></pre>
<a href="http://11011.net/software/vspaste"></a>

<p>I have found that the VM creation is not consistently successful on the first pass, so I have added the while loop. Since adding that, I have not had any issues.</p>

<p>I hope these help. They should be easy to change if you prefer snapshots versus differencing disks. Thanks to James O’Neill for creating this library. It makes administering Hyper-V much easier. It is available via <a title="CodePlex" href="http://www.codeplex.com/" target="_blank">CodePlex</a>, where the latest release, updates, and forum support can be found. </p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Installing Windows 7</title>
		<link>http://elegantcode.com/2009/02/09/installing-windows-7/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=installing-windows-7</link>
		<comments>http://elegantcode.com/2009/02/09/installing-windows-7/#comments</comments>
		<pubDate>Mon, 09 Feb 2009 21:14:36 +0000</pubDate>
		<dc:creator>Alex Mueller</dc:creator>
				<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Operating Systems]]></category>
		<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/02/09/installing-windows-7/</guid>
		<description><![CDATA[The short story is this. If you are accessing Windows 7 from your MSDN subscriptions, save yourself time and frustration by installing the Windows 7 Beta, not the Windows 7 Beta Checked Build. See available downloads here. This past weekend, I decided to upgrade my work laptop from Vista Enterprise to Windows 7 Ultimate Beta. [...]]]></description>
			<content:encoded><![CDATA[<p>The short story is this. If you are accessing Windows 7 from your MSDN subscriptions, save yourself time and frustration by installing the Windows 7 Beta, not the Windows 7 Beta Checked Build. <a href="http://msdn.microsoft.com/en-us/subscriptions/cc137115.aspx" target="_blank">See available downloads here</a>.</p>  <p>This past weekend, I decided to upgrade my work laptop from Vista Enterprise to Windows 7 Ultimate Beta. I was unable to upgrade from Vista Enterprise to 7 Ultimate because that action is not supported. I then tried to upgrade from Enterprise to 7 Enterprise, but I was unable to upgrade from a staged build to a non-staged build. I decided to repave entirely, choosing Windows 7 Ultimate Beta, and I tried to do all of this on a Friday afternoon, two hours before leaving.</p>  <p>I installed Windows 7 Beta Checked Build (x86) - DVD (English), last updated on January 14, 2009,&#160; from my MSDN subscription. I did not install an internal build. Instead, I decided to go with what is publicly available via MSDN. </p>  <p>Why did I go with a <a href="http://msdn.microsoft.com/en-us/library/ms792442.aspx" target="_blank">Checked Build</a>? Because I failed to read the details describing it. What it cost me in time and frustration, I gain in valuable learning experiences. So it was not a total loss. I received a number of buggy issues with the checked build, mainly the inability for Windows Update to properly download all of my necessary updates, including my video drivers and smart card reader, where the latter enables me to remotely access my work domain. </p>  <p>I gave up and decided to download and install the Windows 7 Beta – DVD (English). Everything works great. I was able to get online, download all of my updates, and connect to my work domain. No issues found so far, and no annoying assertion error popups. </p>  <p>My favorite Windows 7 feature so far (non-UI related) is that PowerShell 2.0 is installed by default. PowerShell 2.0 provides more functionality for remoting, among other enhancements.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/02/09/installing-windows-7/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>PowerShell Documentation</title>
		<link>http://elegantcode.com/2008/12/17/powershell-documentation/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-documentation</link>
		<comments>http://elegantcode.com/2008/12/17/powershell-documentation/#comments</comments>
		<pubDate>Wed, 17 Dec 2008 20:36:54 +0000</pubDate>
		<dc:creator>Alex Mueller</dc:creator>
				<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/12/17/powershell-documentation/</guid>
		<description><![CDATA[PowerShell documentation, you are too honest. Get-Help Remove-Item -Full As I was retrieving information on "Remove-Item," this is what I came across. There is more detail beyond what I am showing, but pay attention to what is bolded. NAME&#160;&#160;&#160; Remove-Item SYNOPSIS&#160;&#160;&#160; Deletes the specified items. SYNTAX&#160;&#160;&#160; Remove-Item [-path] &#60;string[]&#62; [-recurse] [-force] [-include &#60;string[]&#62;] [-&#160;&#160;&#160; exclude [...]]]></description>
			<content:encoded><![CDATA[<p>PowerShell documentation, you are too honest. </p> <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:F2210F5F-69EB-4d4c-AFF7-B8A050E9CC72:2ed0ad7a-f3da-498d-a817-1bb0c8b8f8c3" class="wlWriterSmartContent"><pre  style="width:100%;;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #000000;">Get</span><span style="color: #000000;">-</span><span style="color: #000000;">Help Remove</span><span style="color: #000000;">-</span><span style="color: #000000;">Item </span><span style="color: #000000;">-</span><span style="color: #000000;">Full</span></div></pre></div>
<p>As I was retrieving information on "Remove-Item," this is what I came across. There is more detail beyond what I am showing, but pay attention to what is <strong>bolded</strong>. </p>
<blockquote>
<p>NAME<br>&nbsp;&nbsp;&nbsp; Remove-Item 
<p>SYNOPSIS<br>&nbsp;&nbsp;&nbsp; Deletes the specified items. 
<p>SYNTAX<br>&nbsp;&nbsp;&nbsp; Remove-Item [-path] &lt;string[]&gt; [-recurse] [-force] [-include &lt;string[]&gt;] [-<br>&nbsp;&nbsp;&nbsp; exclude &lt;string[]&gt;] [-filter &lt;string&gt;] [-credential &lt;PSCredential&gt;] [-whatI<br>&nbsp;&nbsp;&nbsp; f] [-confirm] [&lt;CommonParameters&gt;] 
<p>&nbsp;&nbsp;&nbsp; Remove-Item [-literalPath] &lt;string[]&gt; [-recurse] [-force] [-include &lt;string<br>&nbsp;&nbsp;&nbsp; []&gt;] [-exclude &lt;string[]&gt;] [-filter &lt;string&gt;] [-credential &lt;PSCredential&gt;]<br>&nbsp;&nbsp;&nbsp; [-whatIf] [-confirm] [&lt;CommonParameters&gt;] 
<p>DETAILED DESCRIPTION<br>&nbsp;&nbsp;&nbsp; The Remove-Item cmdlet deletes one or more items. Because it is supported b<br>&nbsp;&nbsp;&nbsp; y many providers, it can delete many different types of items, including fi<br>&nbsp;&nbsp;&nbsp; les, directories, registry keys, variables, aliases, certificates, and func<br>&nbsp;&nbsp;&nbsp; tions. 
<p>PARAMETERS<br>&nbsp;&nbsp;&nbsp; -path &lt;string[]&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Specifies a path to the items being removed. Wildcards are permitted. T<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; he parameter name ("-Path") is optional. 
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Required?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; true<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Position?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 1<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Default value&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; N/A - The path must be specified<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept pipeline input?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; true (ByValue, ByPropertyName)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept wildcard characters?&nbsp; true 
<p>&nbsp;&nbsp;&nbsp; -recurse &lt;SwitchParameter&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Deletes the items in the specified locations and in all child items of<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; the locations. 
<p><strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; The Recurse parameter in this cmdlet does not work properly. </strong>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Required?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; false<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Position?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; named<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Default value&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; False<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept pipeline input?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; false<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept wildcard characters?&nbsp; false 
<p><strong></strong>&nbsp;</p></blockquote>
<p>"Hmmm... Am I feeling lucky? Ahhh, what the hell, let's do it."</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:F2210F5F-69EB-4d4c-AFF7-B8A050E9CC72:a3ee0edf-63f8-43fc-a4fb-22c6277656f8" class="wlWriterSmartContent"><pre  style="width:100%;;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #000000;">Remove</span><span style="color: #000000;">-</span><span style="color: #000000;">Item </span><span style="color: #800000;">&quot;</span><span style="color: #800000;">C:\</span><span style="color: #800000;">&quot;</span><span style="color: #000000;"> </span><span style="color: #000000;">-</span><span style="color: #000000;">Recurse</span></div></pre></div>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/12/17/powershell-documentation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Automate Daily Tasks with PowerShell</title>
	<atom:link href="http://elegantcode.com/category/microsoft/powershell/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Elegant Code &#187; PowerShell</title>
	<atom:link href="http://elegantcode.com/category/microsoft/powershell/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Silverlight Profiling PowerShell helper.</title>
		<link>http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=silverlight-profiling-powershell-helper</link>
		<comments>http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/#comments</comments>
		<pubDate>Sat, 15 May 2010 16:47:22 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/</guid>
		<description><![CDATA[I was playing around with some Silverlight profiling the other night to see if I could find any obvious issues with my open source project StatLight and wound up writing a little script in PowerShell I hoped someone might find helpful. But I didn’t know you could profile a Silverlight app. I didn’t until I [...]]]></description>
			<content:encoded><![CDATA[<p>I was playing around with some Silverlight profiling the other night to see if I could find any obvious issues with my open source project <a href="http://statlight.net" target="_blank">StatLight</a> and wound up writing a little script in PowerShell I hoped someone might find helpful.</p>  <h4>But I didn’t know you could profile a Silverlight app.</h4>  <p>I didn’t until I started doing some digging online. Now, the Silverlight profiling story (at least from what I’ve seen/tried) is not near the easy of say <a href="http://www.red-gate.com/products/ants_performance_profiler/index.htm">Redgate ANTS Performance Profiler</a>. However, it’s do-able. (And with this helper script – hopefully a little simpler?)</p>  <h4>How can I profile a Silverlight Application?</h4>  <p>I would recommend you read the following blog, which explains one way of doing it very well.</p>  <p><a title="http://blogs.msdn.com/profiler/archive/2010/04/26/vs2010-silverlight-4-profiling.aspx" href="http://blogs.msdn.com/profiler/archive/2010/04/26/vs2010-silverlight-4-profiling.aspx">http://blogs.msdn.com/profiler/archive/2010/04/26/vs2010-silverlight-4-profiling.aspx</a></p>  <h4>So… what’s this script for?</h4>  <p>If you read the blog above, or have done this before, then you probably noticed that there was quite a series of commands you had to execute before you could wind up with a performance report. </p>  <p>I threw together a quick little PowerShell script in an attempt to automate smooth out the process.</p>  <h4>Hot do I use it?</h4>  <ol>   <li>Download the script &amp; save it somewhere. <a href="http://github.com/staxmanade/Scripts/blob/master/SilverlightProfiler.ps1"><strong>http://github.com/staxmanade/Scripts/blob/master/SilverlightProfiler.ps1</strong></a> </li>    <li>Open the PowerShell console. cd to the directory your xap/assemblies are stored.      <br />(EX: {myProject}\Bin\Debug\ ) </li>    <li>Execute:      <br />{pathToScript}\SilverlightProfiler.ps1 -urlPath &quot;{myProject}\Bin\Debug\TestPage.html&quot; </li>    <li>When your done profiling press enter to signal that your done.      <p></p> Once complete, it will print the location your profiling report was saved. You can then open it with Visual Studio.</li> </ol>  <h5>Couple of disclaimers.</h5>  <ul>   <li>Some paths are hard-coded to my x86 machine. </li>    <li>I had troubles running the built in visual studio .bat files (from powershell) that are supposed to set the environment variables. So I extracted out what vars I could find to make it work. </li>    <li>I’m not a profiling expert – just hacked this together to get it to work for me.</li> </ul>  <p>I hope this is useful, and if you know of a better way, I’m always interested in hearing your feedback.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Powershell: Load assembly without locking file.</title>
		<link>http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-load-assembly-without-locking-file</link>
		<comments>http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/#comments</comments>
		<pubDate>Wed, 23 Dec 2009 05:40:23 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/</guid>
		<description><![CDATA[I have a set of PowerShell build scripts and ran into a case where I needed to load an assembly (to get the assembly’s version) and still (at a later time) work with the assembly file on disk. A typical way to load an assembly within PowerShell is to use the Assembly.LoadFrom(filePath) # Powershell [System.Reflection.Assembly]::LoadFrom($assemblyPath) [...]]]></description>
			<content:encoded><![CDATA[<p>I have a set of PowerShell build scripts and ran into a case where I needed to load an assembly (to get the assembly’s version) and still (at a later time) work with the assembly file on disk.</p>  <p>A typical way to load an assembly within PowerShell is to use the Assembly.LoadFrom(filePath)</p>  <blockquote>   <p># Powershell</p>    <p>[System.Reflection.Assembly]::LoadFrom($assemblyPath)</p> </blockquote>  <p><a href="http://elegantcode.com/wp-content/uploads/2009/12/image9.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://elegantcode.com/wp-content/uploads/2009/12/image_thumb9.png" width="690" height="391" /></a> </p>  <p>Except the problem with this (in my case) was it would <strong>lock the file for the lifespan of the PowerShell console instance</strong>. I didn’t want to have to close and re-open the PowerShell console every time I need to run a build so there had to be a work-around for this.</p>  <p>After searching the web for a solution, I couldn’t find anything that was “easy” and worth the effort to get it to work.</p>  <blockquote>   <p>EX: One solution was to create a new AppDomain, do the necessary work and the close the AppDomain which would release the lock on the file.</p>    <p>I’ve never done this myself, and even thought there is example code out there to get this accomplished, it just seemed over the top for what I was trying to do, and back to my previous criteria it wasn’t “worth the effort to get it to work”</p> </blockquote>  <p>Then I remembered in a previous life I used an overload that took an array of bytes to load the an assembly.</p>  <blockquote>   <p>[System.Reflection.Assembly]::Load($assemblyBytes)</p> </blockquote>  <p>After spiking it in PowerShell with the below test. I was quite happy with the solution, so I thought I’d throw it out there.</p>  <p>Just stream the assembly from disk into a byte array manually, and call assembly load from there.</p>  <p>Here’s my test case which shows that the file is not locked after it was loaded into the PowerShell runtime</p>  <pre>$file = &quot;.\Moq.dll&quot;
$tempFileName = &quot;.\Moq-Renamed.dll&quot;

$fileStream = ([System.IO.FileInfo] (Get-Item $file)).OpenRead();
$assemblyBytes = new-object byte[] $fileStream.Length
$fileStream.Read($assemblyBytes, 0, $fileStream.Length);
$fileStream.Close();

$assemblyLoaded = [System.Reflection.Assembly]::Load($assemblyBytes);

# notice that we can move the file on disk after 
# it's loaded into the powershell runtime
Move-Item $file $tempFileName
Move-Item $tempFileName $file 

# and display the assembly information to show we still have it in memory
echo $assemblyLoaded</pre>

<p>After that test passed, and the main reason I wanted to do this, I wrote the “get-assembly-version” PowerShell function.</p>

<pre><strike>function get-assembly-version() {
    param([string] $file)
    
    # load the assembly bytes quickly - as to not lock the file for too long
    $fileStream = ([System.IO.FileInfo] (Get-Item $file)).OpenRead()
    $assemblyBytes = new-object byte[] $fileStream.Length
    $fileStream.Read($assemblyBytes, 0, $fileStream.Length) | Out-Null #out null this because this function should only return the version &amp; this call was outputting some garbage number
    $fileStream.Close()
    
    # return the version of the assembly
    [System.Reflection.Assembly]::Load($assemblyBytes).GetName().Version;
}

$version = get-assembly-version(&quot;.\Moq.dll&quot;)

echo &quot;Loaded v$($version.Major).$($version.Minor).$($version.Build).$($version.Revision) version of $file&quot;</strike></pre>
Hope this helps someone out there! 

<p></p>

<p>&#160;</p>

<p><strong>UPDATE:</strong></p>

<p><a href="http://achuebrigens.wordpress.com">Martin</a> commented below on a much better solution to the assembly version info problem. Amazing how complicated we can make things if we don’t know the path.</p>

<pre>
function get-assembly-version() {
    param([string] $file)
    
    $version = [System.Reflection.AssemblyName]::GetAssemblyName($file).Version;
    
    #format the version and output it...
    $version
}</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Integration Test Brought to you by Powershell &amp; NUnit &#8211; with a Little Specification Syntax for Flavoring</title>
		<link>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring</link>
		<comments>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/#comments</comments>
		<pubDate>Mon, 26 Oct 2009 05:00:40 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/</guid>
		<description><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about Fluent Specification Extensions in a past blog. Recently I wanted to execute a PowerShell script [...]]]></description>
			<content:encoded><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about <a href="http://staxmanade.blogspot.com/2009/02/fluent-specification-extensions.html">Fluent Specification Extensions</a> in a past blog.

Recently I wanted to execute a PowerShell script to do some automated <a href="http://en.wikipedia.org/wiki/Functional_testing">functional testing</a>. I wanted to execute an application and apply some assertions on the output of the software(basically running a console app, parse the xml output and assert on values in the output).
<blockquote>FYI: I’m very new to PowerShell, so any suggestions on how I implemented the below are welcome…</blockquote>
I’ve seen a couple examples of writing test assertions in PowerShell out there. One example is <a href="http://www.psunit.org/">PSUnit</a>; however, this seemed a little heavy for my needs and not quite the syntactic sugar I was looking for.

Besides the syntax flavor I was desiring, another thing I wanted to do was leverage the power of NUnit.Framework’s assertion capabilities. I like the error messages generated when strings and other objects fail the assertion.
<h5>Examples of end result ShouldLookLike()…</h5>
$true.ShouldBeTrue()
$false.ShouldBeFalse()
"a".ShouldEqual("a")
"a".ShouldNotEqual("b")
<h5><strong>Step 1</strong>: Figure out how to write a C# style <a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx">extension method</a> in PowerShell.</h5>
<blockquote>I found a great blog post describing how to extend any PowerShell object to add extension methods.

<a href="http://bartdesmet.net/blogs/bart/archive/2007/09/06/extension-methods-in-windows-powershell.aspx">Extension Methods in Windows PowerShell</a></blockquote>
In short, to extend types in PowerShell leveraging the <a href="http://msdn.microsoft.com/en-us/library/ms714419(VS.85).aspx">Extended Type System</a>, you need to define them in an xml file and import the method definitions into the PowerShell runtime instance.

Below is PowerShell XML definition for my NUnit Specification Extensions.
<pre class="brush: xml;">&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;Types&gt;
    &lt;Type&gt;
        &lt;Name&gt;System.Object&lt;/Name&gt;
        &lt;Members&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeFalse&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsFalse($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeTrue&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsTrue($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldNotEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreNotEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
        &lt;/Members&gt;
    &lt;/Type&gt;
&lt;/Types&gt;</pre>
<h4></h4>
Take the above XML and save it to a file…
<blockquote>NOTE: the file HAS to be saved with the extension <strong>.ps1xml</strong>

Ex: NunitSpecificationPowerShellExtensions<strong>.ps1xml</strong></blockquote>
<h4></h4>
<h5>Step 2: Load the extended type definition into the PowerShell runtime.</h5>
Once you’ve saved the XML extended types to a file, you need to load it into the PowerShell runtime by executing the command below.
<blockquote>
Update-TypeData -PrependPath NunitSpecificationPowerShellExtensions.ps1xml</blockquote>
Before executing the above statement…Let’s quickly look at a System.String’s members and properties – just to show you what the extension methods look like when applied inside of the runtime.<a href="http://elegantcode.com/wp-content/uploads/2009/10/image3.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb2.png" border="0" alt="image" width="586" height="479" /></a>

After executing the Update-TypeData command you’ll notice there are a number of “ScriptMethod” MemberTypes added to the object.

<a href="http://elegantcode.com/wp-content/uploads/2009/10/image4.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb3.png" border="0" alt="image" width="600" height="580" /></a>

Now if you try to execute one of those newly added extension methods, you may get the following error…

PS C:\&gt; $testVar.<strong>ShouldEqual</strong>("hello world")

Exception calling "ShouldEqual" with "1" argument(s): "<strong>Unable to find type [NUnit.Framework.Assert]: make sure that the

assembly containing this type is loaded.</strong>"

At line:1 char:21

+ $testVar.ShouldEqual &lt;&lt;&lt;&lt; ("hello world")

+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

+ FullyQualifiedErrorId : ScriptMethodRuntimeException

This is because we need to load the NUnit.Framework assembly into the runtime before we can leverage the extension methods.
<blockquote>[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null</blockquote>
Now that the extension methods have been defined and loaded into the runtime, NUnit.Framework is loaded, we can now use the methods on any object that inherits from System.Object (which, as far as I know, is everything in PowerShell).

And now, everything you need in one script (if you have the xml extended type file saved somewhere…)
<pre>#
# Update-TypeData -prependPath C:\Code\NunitSpecificationPowerShellExtensions.ps1xml
#

[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null

$true.ShouldBeTrue()

$false.ShouldBeFalse()

"a".ShouldEqual("a")

"a".ShouldNotEqual("b")</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>PowerShell Management Library for Hyper-V</title>
		<link>http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-management-library-for-hyper-v</link>
		<comments>http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/#comments</comments>
		<pubDate>Wed, 25 Mar 2009 21:46:16 +0000</pubDate>
		<dc:creator>Alex Mueller</dc:creator>
				<category><![CDATA[Hyper-V]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Tools and Utilities]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/</guid>
		<description><![CDATA[I am always looking for tools to allow me to do more by doing less. Administering Hyper-V with PowerShell can be tedious. James O’Neill’s PowerShell Management Library for Hyper-V is a great tool to improve automation of Hyper-V management using PowerShell. As a tester, I am constantly creating new environments, installing our product, taking snapshots, [...]]]></description>
			<content:encoded><![CDATA[<p>I am always looking for tools to allow me to do more by doing less. Administering Hyper-V with PowerShell can be tedious. James O’Neill’s <a href="http://pshyperv.codeplex.com/" target="_blank">PowerShell Management Library for Hyper-V</a> is a great tool to improve automation of Hyper-V management using PowerShell.</p>  <p>As a tester, I am constantly creating new environments, installing our product, taking snapshots, ect. Doing this by hand is a waste of time in my opinion. Doing this with a script makes life easier and frees up my time. </p>  <p>Typically, I prefer to create is to create one VM and to have other VMs inherit from that base image. My second VM (the first child to inherit from the base), I will install daily builds of our product. I will then create a third child, which I use a sandbox. I can easily delete it and recreate as needed without having to install our product over again. I have not consistently found success with using snapshots, so I prefer to use differencing disks. The examples below use differencing disks. </p>  <p>This first code block shows how I am using the PowerShell management library to simply the creation of a base VM. There is nothing magic about it. It’s pretty strait-forward. I create a VM, give it a name, set the CPU count, memory size, network adapters, hard drive, and DVD drive.</p>  <pre class="code"><span style="color: purple">$server </span><span style="color: red">= </span><span style="color: maroon">&quot;my-dev-server&quot;
</span><span style="color: purple">$vmName </span><span style="color: red">= </span><span style="color: maroon">&quot;TestParentVM&quot;
</span><span style="color: purple">$vmVirtualSwitch </span><span style="color: red">= </span><span style="color: maroon">&quot;My Virtual Network&quot;

</span><span style="color: green"># create a new virtual machine
</span><span style="color: purple">$vm </span><span style="color: red">= </span><span style="color: black">New-VM </span><span style="color: purple">$vmName </span><span style="color: black">-server </span><span style="color: purple">$server

</span><span style="color: green"># set cpu count
</span><span style="color: black">Set-VMCPUCount </span><span style="color: purple">$vm </span><span style="color: black">2 -server </span><span style="color: purple">$server

</span><span style="color: green"># set memory size
</span><span style="color: black">Set-VMMemory </span><span style="color: purple">$vm </span><span style="color: black">2 -memory 4GB -server </span><span style="color: purple">$server

</span><span style="color: green"># add a legacy network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch </span><span style="color: black">-legacy

</span><span style="color: green"># add a default VMBus (non-legacy) network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch

</span><span style="color: green"># add the hard drive to the VM
</span><span style="color: black">Add-VMNewHardDisk –vm </span><span style="color: purple">$vm </span><span style="color: black">-controllerID 0 -lun 0 -vhdpath </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmName.vhd&quot; </span><span style="color: black">-size 20GB

</span><span style="color: green"># add the DVD with bootup ISO
</span><span style="color: black">Add-VMDRIVE –vm </span><span style="color: purple">$vm </span><span style="color: black">1 1 -server </span><span style="color: purple">$server </span><span style="color: black">-DVD 

</span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;Operation complete.&quot;</span></pre>
<a href="http://11011.net/software/vspaste"></a>

<p>The next code block will create a differencing disk pointing to the parent created in the previous example. I create the usual, VM, CPU count, ect. What makes this a differencing disk is how the VHD is created by specifying the parent. I do some cleanup in this routine by deleting any previously created VMs or VHDs, and I loop through the creation a failure preventative. </p>

<pre class="code"><span style="color: purple">$server </span><span style="color: red">= </span><span style="color: maroon">&quot;my-dev-server&quot;
</span><span style="color: purple">$vmName </span><span style="color: red">= </span><span style="color: maroon">&quot;TestChildVM&quot;
</span><span style="color: purple">$vmParent </span><span style="color: red">= </span><span style="color: maroon">&quot;TestParentVM&quot;
</span><span style="color: purple">$vmVirtualSwitch </span><span style="color: red">= </span><span style="color: maroon">&quot;My Virtual Network&quot;

</span><span style="color: blue">#region </span><span style="color: black">functions - feel free to move to a separate file

</span><span style="color: blue">Function </span><span style="color: #5f9ea0">DeleteVhd
</span><span style="color: black">{
    </span><span style="color: blue">Param </span><span style="color: black">(</span><span style="color: purple">$pathToVhd</span><span style="color: black">)
    </span><span style="color: green"># delete the disk that was added if it exists
    </span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: #5f9ea0">test-path -path </span><span style="color: purple">$pathToVhd</span><span style="color: black">)
    {
        </span><span style="color: #5f9ea0">Remove-Item -Path </span><span style="color: purple">$pathToVhd </span><span style="color: #5f9ea0">-Force
    </span><span style="color: black">}
}

</span><span style="color: blue">#endregion

</span><span style="color: green"># delete the VHD if it already exists
</span><span style="color: #5f9ea0">DeleteVhd </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmName.vhd&quot;

</span><span style="color: green"># delete the VM if it already exists
</span><span style="color: black">Remove-VM -vm </span><span style="color: purple">$vmName </span><span style="color: black">-server </span><span style="color: purple">$server

</span><span style="color: green"># create a new virtual machine
</span><span style="color: purple">$vm </span><span style="color: red">= </span><span style="color: black">New-VM </span><span style="color: purple">$vmName </span><span style="color: black">-server </span><span style="color: purple">$server

</span><span style="color: green"># get the vm
</span><span style="color: purple">$vm </span><span style="color: red">= </span><span style="color: black">Get-VM </span><span style="color: purple">$vmName

</span><span style="color: green"># set cpu count
</span><span style="color: black">Set-VMCPUCount </span><span style="color: purple">$vm </span><span style="color: black">2 -server </span><span style="color: purple">$server

</span><span style="color: green"># set memory size
</span><span style="color: black">Set-VMMemory </span><span style="color: purple">$vm </span><span style="color: black">2 -memory 4GB -server </span><span style="color: purple">$server

</span><span style="color: green"># get VM Nics available
</span><span style="color: purple">$vmNics </span><span style="color: red">= </span><span style="color: black">Get-VMNic -server </span><span style="color: purple">$server </span><span style="color: black">-vmbus -legacy
</span><span style="color: purple">$vmNicSwitchList </span><span style="color: red">= </span><span style="color: #5f9ea0">New-Object </span><span style="color: maroon">System.Collections.ArrayList

</span><span style="color: green"># get VM Nic Switch available for each VM Nic and add it to our list
</span><span style="color: blue">foreach </span><span style="color: black">(</span><span style="color: purple">$vmNic </span><span style="color: blue">in </span><span style="color: purple">$vmNics</span><span style="color: black">)
{
    </span><span style="color: purple">$vmSwitchElementName </span><span style="color: red">= </span><span style="color: black">(Get-VMNicSwitch </span><span style="color: purple">$vmNic</span><span style="color: black">).ElementName
    </span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">.Contains(</span><span style="color: purple">$vmSwitchElementName</span><span style="color: black">) </span><span style="color: red">-ne </span><span style="color: blue">$true</span><span style="color: black">)
    {
        </span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">.Add(</span><span style="color: purple">$vmSwitchElementName</span><span style="color: black">)
    }
}

</span><span style="color: green"># Use the first available VM Nic Switch - this assumes 
# I do not create more than on per each environment.
</span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">.Count </span><span style="color: red">-gt </span><span style="color: black">0)
{
    </span><span style="color: purple">$vmVirtualSwitch </span><span style="color: red">= </span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">[0]
}

</span><span style="color: green"># add a legacy network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch </span><span style="color: black">-legacy

</span><span style="color: green"># add a default VMBus (non-legacy) network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch

</span><span style="color: green"># add the hard drive to the VM
</span><span style="color: purple">$parent </span><span style="color: red">= </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmParent.vhd&quot;
</span><span style="color: purple">$vhdPath </span><span style="color: red">= </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmName.vhd&quot;
</span><span style="color: black">Add-VMNewHardDisk –vm </span><span style="color: purple">$vm </span><span style="color: black">-controllerID 0 -lun 0 -vhdpath </span><span style="color: purple">$vhdPath </span><span style="color: black">-parent </span><span style="color: purple">$parent

</span><span style="color: green"># get the VM to see if a disk is attached to it, if it is not, then it failed
</span><span style="color: purple">$disks </span><span style="color: red">= </span><span style="color: black">Get-VMDisk -vm </span><span style="color: purple">$vm
$count </span><span style="color: red">= </span><span style="color: black">1

</span><span style="color: green"># if the disk was not successfully added, try and add it again
</span><span style="color: blue">while </span><span style="color: black">(</span><span style="color: purple">$disks </span><span style="color: red">-eq </span><span style="color: purple">$null </span><span style="color: red">-and </span><span style="color: purple">$count </span><span style="color: red">-le </span><span style="color: black">5)
{
    </span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;RETRY $count - The disk was not properly added. Attempting to retry.&quot;
    
    </span><span style="color: green"># delete the disk that was added
    </span><span style="color: #5f9ea0">DeleteVhd </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmName.vhd&quot;
    
    </span><span style="color: black">Add-VMNewHardDisk –vm </span><span style="color: purple">$vm </span><span style="color: black">-controllerID 0 -lun 0 -vhdpath </span><span style="color: purple">$vhdPath </span><span style="color: black">-parent </span><span style="color: purple">$parent
    
    $disks </span><span style="color: red">= </span><span style="color: black">Get-VMDisk -vm </span><span style="color: purple">$vm
    $count</span><span style="color: red">++
</span><span style="color: black">}

</span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: purple">$disks </span><span style="color: red">-eq </span><span style="color: purple">$null</span><span style="color: black">)
{
    </span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;Operation failed to create this virtual machine. Contact an admin.&quot;
</span><span style="color: black">}
</span><span style="color: blue">else
</span><span style="color: black">{
    </span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;Operation completed successfully. Attempting to start the VM.&quot;
    </span><span style="color: black">Start-VM -vm </span><span style="color: purple">$vm </span><span style="color: black">-wait
}</span></pre>
<a href="http://11011.net/software/vspaste"></a>

<p>I have found that the VM creation is not consistently successful on the first pass, so I have added the while loop. Since adding that, I have not had any issues.</p>

<p>I hope these help. They should be easy to change if you prefer snapshots versus differencing disks. Thanks to James O’Neill for creating this library. It makes administering Hyper-V much easier. It is available via <a title="CodePlex" href="http://www.codeplex.com/" target="_blank">CodePlex</a>, where the latest release, updates, and forum support can be found. </p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Installing Windows 7</title>
		<link>http://elegantcode.com/2009/02/09/installing-windows-7/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=installing-windows-7</link>
		<comments>http://elegantcode.com/2009/02/09/installing-windows-7/#comments</comments>
		<pubDate>Mon, 09 Feb 2009 21:14:36 +0000</pubDate>
		<dc:creator>Alex Mueller</dc:creator>
				<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Operating Systems]]></category>
		<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/02/09/installing-windows-7/</guid>
		<description><![CDATA[The short story is this. If you are accessing Windows 7 from your MSDN subscriptions, save yourself time and frustration by installing the Windows 7 Beta, not the Windows 7 Beta Checked Build. See available downloads here. This past weekend, I decided to upgrade my work laptop from Vista Enterprise to Windows 7 Ultimate Beta. [...]]]></description>
			<content:encoded><![CDATA[<p>The short story is this. If you are accessing Windows 7 from your MSDN subscriptions, save yourself time and frustration by installing the Windows 7 Beta, not the Windows 7 Beta Checked Build. <a href="http://msdn.microsoft.com/en-us/subscriptions/cc137115.aspx" target="_blank">See available downloads here</a>.</p>  <p>This past weekend, I decided to upgrade my work laptop from Vista Enterprise to Windows 7 Ultimate Beta. I was unable to upgrade from Vista Enterprise to 7 Ultimate because that action is not supported. I then tried to upgrade from Enterprise to 7 Enterprise, but I was unable to upgrade from a staged build to a non-staged build. I decided to repave entirely, choosing Windows 7 Ultimate Beta, and I tried to do all of this on a Friday afternoon, two hours before leaving.</p>  <p>I installed Windows 7 Beta Checked Build (x86) - DVD (English), last updated on January 14, 2009,&#160; from my MSDN subscription. I did not install an internal build. Instead, I decided to go with what is publicly available via MSDN. </p>  <p>Why did I go with a <a href="http://msdn.microsoft.com/en-us/library/ms792442.aspx" target="_blank">Checked Build</a>? Because I failed to read the details describing it. What it cost me in time and frustration, I gain in valuable learning experiences. So it was not a total loss. I received a number of buggy issues with the checked build, mainly the inability for Windows Update to properly download all of my necessary updates, including my video drivers and smart card reader, where the latter enables me to remotely access my work domain. </p>  <p>I gave up and decided to download and install the Windows 7 Beta – DVD (English). Everything works great. I was able to get online, download all of my updates, and connect to my work domain. No issues found so far, and no annoying assertion error popups. </p>  <p>My favorite Windows 7 feature so far (non-UI related) is that PowerShell 2.0 is installed by default. PowerShell 2.0 provides more functionality for remoting, among other enhancements.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/02/09/installing-windows-7/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>PowerShell Documentation</title>
		<link>http://elegantcode.com/2008/12/17/powershell-documentation/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-documentation</link>
		<comments>http://elegantcode.com/2008/12/17/powershell-documentation/#comments</comments>
		<pubDate>Wed, 17 Dec 2008 20:36:54 +0000</pubDate>
		<dc:creator>Alex Mueller</dc:creator>
				<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/12/17/powershell-documentation/</guid>
		<description><![CDATA[PowerShell documentation, you are too honest. Get-Help Remove-Item -Full As I was retrieving information on "Remove-Item," this is what I came across. There is more detail beyond what I am showing, but pay attention to what is bolded. NAME&#160;&#160;&#160; Remove-Item SYNOPSIS&#160;&#160;&#160; Deletes the specified items. SYNTAX&#160;&#160;&#160; Remove-Item [-path] &#60;string[]&#62; [-recurse] [-force] [-include &#60;string[]&#62;] [-&#160;&#160;&#160; exclude [...]]]></description>
			<content:encoded><![CDATA[<p>PowerShell documentation, you are too honest. </p> <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:F2210F5F-69EB-4d4c-AFF7-B8A050E9CC72:2ed0ad7a-f3da-498d-a817-1bb0c8b8f8c3" class="wlWriterSmartContent"><pre  style="width:100%;;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #000000;">Get</span><span style="color: #000000;">-</span><span style="color: #000000;">Help Remove</span><span style="color: #000000;">-</span><span style="color: #000000;">Item </span><span style="color: #000000;">-</span><span style="color: #000000;">Full</span></div></pre></div>
<p>As I was retrieving information on "Remove-Item," this is what I came across. There is more detail beyond what I am showing, but pay attention to what is <strong>bolded</strong>. </p>
<blockquote>
<p>NAME<br>&nbsp;&nbsp;&nbsp; Remove-Item 
<p>SYNOPSIS<br>&nbsp;&nbsp;&nbsp; Deletes the specified items. 
<p>SYNTAX<br>&nbsp;&nbsp;&nbsp; Remove-Item [-path] &lt;string[]&gt; [-recurse] [-force] [-include &lt;string[]&gt;] [-<br>&nbsp;&nbsp;&nbsp; exclude &lt;string[]&gt;] [-filter &lt;string&gt;] [-credential &lt;PSCredential&gt;] [-whatI<br>&nbsp;&nbsp;&nbsp; f] [-confirm] [&lt;CommonParameters&gt;] 
<p>&nbsp;&nbsp;&nbsp; Remove-Item [-literalPath] &lt;string[]&gt; [-recurse] [-force] [-include &lt;string<br>&nbsp;&nbsp;&nbsp; []&gt;] [-exclude &lt;string[]&gt;] [-filter &lt;string&gt;] [-credential &lt;PSCredential&gt;]<br>&nbsp;&nbsp;&nbsp; [-whatIf] [-confirm] [&lt;CommonParameters&gt;] 
<p>DETAILED DESCRIPTION<br>&nbsp;&nbsp;&nbsp; The Remove-Item cmdlet deletes one or more items. Because it is supported b<br>&nbsp;&nbsp;&nbsp; y many providers, it can delete many different types of items, including fi<br>&nbsp;&nbsp;&nbsp; les, directories, registry keys, variables, aliases, certificates, and func<br>&nbsp;&nbsp;&nbsp; tions. 
<p>PARAMETERS<br>&nbsp;&nbsp;&nbsp; -path &lt;string[]&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Specifies a path to the items being removed. Wildcards are permitted. T<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; he parameter name ("-Path") is optional. 
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Required?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; true<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Position?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 1<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Default value&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; N/A - The path must be specified<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept pipeline input?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; true (ByValue, ByPropertyName)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept wildcard characters?&nbsp; true 
<p>&nbsp;&nbsp;&nbsp; -recurse &lt;SwitchParameter&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Deletes the items in the specified locations and in all child items of<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; the locations. 
<p><strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; The Recurse parameter in this cmdlet does not work properly. </strong>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Required?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; false<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Position?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; named<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Default value&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; False<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept pipeline input?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; false<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept wildcard characters?&nbsp; false 
<p><strong></strong>&nbsp;</p></blockquote>
<p>"Hmmm... Am I feeling lucky? Ahhh, what the hell, let's do it."</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:F2210F5F-69EB-4d4c-AFF7-B8A050E9CC72:a3ee0edf-63f8-43fc-a4fb-22c6277656f8" class="wlWriterSmartContent"><pre  style="width:100%;;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #000000;">Remove</span><span style="color: #000000;">-</span><span style="color: #000000;">Item </span><span style="color: #800000;">&quot;</span><span style="color: #800000;">C:\</span><span style="color: #800000;">&quot;</span><span style="color: #000000;"> </span><span style="color: #000000;">-</span><span style="color: #000000;">Recurse</span></div></pre></div>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/12/17/powershell-documentation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Automate Daily Tasks with PowerShell</title>
		<link>http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=silverlight-profiling-powershell-helper</link>
		<comments>http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/#comments</comments>
		<pubDate>Sat, 15 May 2010 16:47:22 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/</guid>
		<description><![CDATA[I was playing around with some Silverlight profiling the other night to see if I could find any obvious issues with my open source project StatLight and wound up writing a little script in PowerShell I hoped someone might find helpful. But I didn’t know you could profile a Silverlight app. I didn’t until I [...]]]></description>
			<content:encoded><![CDATA[<p>I was playing around with some Silverlight profiling the other night to see if I could find any obvious issues with my open source project <a href="http://statlight.net" target="_blank">StatLight</a> and wound up writing a little script in PowerShell I hoped someone might find helpful.</p>  <h4>But I didn’t know you could profile a Silverlight app.</h4>  <p>I didn’t until I started doing some digging online. Now, the Silverlight profiling story (at least from what I’ve seen/tried) is not near the easy of say <a href="http://www.red-gate.com/products/ants_performance_profiler/index.htm">Redgate ANTS Performance Profiler</a>. However, it’s do-able. (And with this helper script – hopefully a little simpler?)</p>  <h4>How can I profile a Silverlight Application?</h4>  <p>I would recommend you read the following blog, which explains one way of doing it very well.</p>  <p><a title="http://blogs.msdn.com/profiler/archive/2010/04/26/vs2010-silverlight-4-profiling.aspx" href="http://blogs.msdn.com/profiler/archive/2010/04/26/vs2010-silverlight-4-profiling.aspx">http://blogs.msdn.com/profiler/archive/2010/04/26/vs2010-silverlight-4-profiling.aspx</a></p>  <h4>So… what’s this script for?</h4>  <p>If you read the blog above, or have done this before, then you probably noticed that there was quite a series of commands you had to execute before you could wind up with a performance report. </p>  <p>I threw together a quick little PowerShell script in an attempt to automate smooth out the process.</p>  <h4>Hot do I use it?</h4>  <ol>   <li>Download the script &amp; save it somewhere. <a href="http://github.com/staxmanade/Scripts/blob/master/SilverlightProfiler.ps1"><strong>http://github.com/staxmanade/Scripts/blob/master/SilverlightProfiler.ps1</strong></a> </li>    <li>Open the PowerShell console. cd to the directory your xap/assemblies are stored.      <br />(EX: {myProject}\Bin\Debug\ ) </li>    <li>Execute:      <br />{pathToScript}\SilverlightProfiler.ps1 -urlPath &quot;{myProject}\Bin\Debug\TestPage.html&quot; </li>    <li>When your done profiling press enter to signal that your done.      <p></p> Once complete, it will print the location your profiling report was saved. You can then open it with Visual Studio.</li> </ol>  <h5>Couple of disclaimers.</h5>  <ul>   <li>Some paths are hard-coded to my x86 machine. </li>    <li>I had troubles running the built in visual studio .bat files (from powershell) that are supposed to set the environment variables. So I extracted out what vars I could find to make it work. </li>    <li>I’m not a profiling expert – just hacked this together to get it to work for me.</li> </ul>  <p>I hope this is useful, and if you know of a better way, I’m always interested in hearing your feedback.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Elegant Code &#187; PowerShell</title>
	<atom:link href="http://elegantcode.com/category/microsoft/powershell/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Silverlight Profiling PowerShell helper.</title>
		<link>http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=silverlight-profiling-powershell-helper</link>
		<comments>http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/#comments</comments>
		<pubDate>Sat, 15 May 2010 16:47:22 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/</guid>
		<description><![CDATA[I was playing around with some Silverlight profiling the other night to see if I could find any obvious issues with my open source project StatLight and wound up writing a little script in PowerShell I hoped someone might find helpful. But I didn’t know you could profile a Silverlight app. I didn’t until I [...]]]></description>
			<content:encoded><![CDATA[<p>I was playing around with some Silverlight profiling the other night to see if I could find any obvious issues with my open source project <a href="http://statlight.net" target="_blank">StatLight</a> and wound up writing a little script in PowerShell I hoped someone might find helpful.</p>  <h4>But I didn’t know you could profile a Silverlight app.</h4>  <p>I didn’t until I started doing some digging online. Now, the Silverlight profiling story (at least from what I’ve seen/tried) is not near the easy of say <a href="http://www.red-gate.com/products/ants_performance_profiler/index.htm">Redgate ANTS Performance Profiler</a>. However, it’s do-able. (And with this helper script – hopefully a little simpler?)</p>  <h4>How can I profile a Silverlight Application?</h4>  <p>I would recommend you read the following blog, which explains one way of doing it very well.</p>  <p><a title="http://blogs.msdn.com/profiler/archive/2010/04/26/vs2010-silverlight-4-profiling.aspx" href="http://blogs.msdn.com/profiler/archive/2010/04/26/vs2010-silverlight-4-profiling.aspx">http://blogs.msdn.com/profiler/archive/2010/04/26/vs2010-silverlight-4-profiling.aspx</a></p>  <h4>So… what’s this script for?</h4>  <p>If you read the blog above, or have done this before, then you probably noticed that there was quite a series of commands you had to execute before you could wind up with a performance report. </p>  <p>I threw together a quick little PowerShell script in an attempt to automate smooth out the process.</p>  <h4>Hot do I use it?</h4>  <ol>   <li>Download the script &amp; save it somewhere. <a href="http://github.com/staxmanade/Scripts/blob/master/SilverlightProfiler.ps1"><strong>http://github.com/staxmanade/Scripts/blob/master/SilverlightProfiler.ps1</strong></a> </li>    <li>Open the PowerShell console. cd to the directory your xap/assemblies are stored.      <br />(EX: {myProject}\Bin\Debug\ ) </li>    <li>Execute:      <br />{pathToScript}\SilverlightProfiler.ps1 -urlPath &quot;{myProject}\Bin\Debug\TestPage.html&quot; </li>    <li>When your done profiling press enter to signal that your done.      <p></p> Once complete, it will print the location your profiling report was saved. You can then open it with Visual Studio.</li> </ol>  <h5>Couple of disclaimers.</h5>  <ul>   <li>Some paths are hard-coded to my x86 machine. </li>    <li>I had troubles running the built in visual studio .bat files (from powershell) that are supposed to set the environment variables. So I extracted out what vars I could find to make it work. </li>    <li>I’m not a profiling expert – just hacked this together to get it to work for me.</li> </ul>  <p>I hope this is useful, and if you know of a better way, I’m always interested in hearing your feedback.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Powershell: Load assembly without locking file.</title>
		<link>http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-load-assembly-without-locking-file</link>
		<comments>http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/#comments</comments>
		<pubDate>Wed, 23 Dec 2009 05:40:23 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/</guid>
		<description><![CDATA[I have a set of PowerShell build scripts and ran into a case where I needed to load an assembly (to get the assembly’s version) and still (at a later time) work with the assembly file on disk. A typical way to load an assembly within PowerShell is to use the Assembly.LoadFrom(filePath) # Powershell [System.Reflection.Assembly]::LoadFrom($assemblyPath) [...]]]></description>
			<content:encoded><![CDATA[<p>I have a set of PowerShell build scripts and ran into a case where I needed to load an assembly (to get the assembly’s version) and still (at a later time) work with the assembly file on disk.</p>  <p>A typical way to load an assembly within PowerShell is to use the Assembly.LoadFrom(filePath)</p>  <blockquote>   <p># Powershell</p>    <p>[System.Reflection.Assembly]::LoadFrom($assemblyPath)</p> </blockquote>  <p><a href="http://elegantcode.com/wp-content/uploads/2009/12/image9.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://elegantcode.com/wp-content/uploads/2009/12/image_thumb9.png" width="690" height="391" /></a> </p>  <p>Except the problem with this (in my case) was it would <strong>lock the file for the lifespan of the PowerShell console instance</strong>. I didn’t want to have to close and re-open the PowerShell console every time I need to run a build so there had to be a work-around for this.</p>  <p>After searching the web for a solution, I couldn’t find anything that was “easy” and worth the effort to get it to work.</p>  <blockquote>   <p>EX: One solution was to create a new AppDomain, do the necessary work and the close the AppDomain which would release the lock on the file.</p>    <p>I’ve never done this myself, and even thought there is example code out there to get this accomplished, it just seemed over the top for what I was trying to do, and back to my previous criteria it wasn’t “worth the effort to get it to work”</p> </blockquote>  <p>Then I remembered in a previous life I used an overload that took an array of bytes to load the an assembly.</p>  <blockquote>   <p>[System.Reflection.Assembly]::Load($assemblyBytes)</p> </blockquote>  <p>After spiking it in PowerShell with the below test. I was quite happy with the solution, so I thought I’d throw it out there.</p>  <p>Just stream the assembly from disk into a byte array manually, and call assembly load from there.</p>  <p>Here’s my test case which shows that the file is not locked after it was loaded into the PowerShell runtime</p>  <pre>$file = &quot;.\Moq.dll&quot;
$tempFileName = &quot;.\Moq-Renamed.dll&quot;

$fileStream = ([System.IO.FileInfo] (Get-Item $file)).OpenRead();
$assemblyBytes = new-object byte[] $fileStream.Length
$fileStream.Read($assemblyBytes, 0, $fileStream.Length);
$fileStream.Close();

$assemblyLoaded = [System.Reflection.Assembly]::Load($assemblyBytes);

# notice that we can move the file on disk after 
# it's loaded into the powershell runtime
Move-Item $file $tempFileName
Move-Item $tempFileName $file 

# and display the assembly information to show we still have it in memory
echo $assemblyLoaded</pre>

<p>After that test passed, and the main reason I wanted to do this, I wrote the “get-assembly-version” PowerShell function.</p>

<pre><strike>function get-assembly-version() {
    param([string] $file)
    
    # load the assembly bytes quickly - as to not lock the file for too long
    $fileStream = ([System.IO.FileInfo] (Get-Item $file)).OpenRead()
    $assemblyBytes = new-object byte[] $fileStream.Length
    $fileStream.Read($assemblyBytes, 0, $fileStream.Length) | Out-Null #out null this because this function should only return the version &amp; this call was outputting some garbage number
    $fileStream.Close()
    
    # return the version of the assembly
    [System.Reflection.Assembly]::Load($assemblyBytes).GetName().Version;
}

$version = get-assembly-version(&quot;.\Moq.dll&quot;)

echo &quot;Loaded v$($version.Major).$($version.Minor).$($version.Build).$($version.Revision) version of $file&quot;</strike></pre>
Hope this helps someone out there! 

<p></p>

<p>&#160;</p>

<p><strong>UPDATE:</strong></p>

<p><a href="http://achuebrigens.wordpress.com">Martin</a> commented below on a much better solution to the assembly version info problem. Amazing how complicated we can make things if we don’t know the path.</p>

<pre>
function get-assembly-version() {
    param([string] $file)
    
    $version = [System.Reflection.AssemblyName]::GetAssemblyName($file).Version;
    
    #format the version and output it...
    $version
}</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Integration Test Brought to you by Powershell &amp; NUnit &#8211; with a Little Specification Syntax for Flavoring</title>
		<link>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring</link>
		<comments>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/#comments</comments>
		<pubDate>Mon, 26 Oct 2009 05:00:40 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/</guid>
		<description><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about Fluent Specification Extensions in a past blog. Recently I wanted to execute a PowerShell script [...]]]></description>
			<content:encoded><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about <a href="http://staxmanade.blogspot.com/2009/02/fluent-specification-extensions.html">Fluent Specification Extensions</a> in a past blog.

Recently I wanted to execute a PowerShell script to do some automated <a href="http://en.wikipedia.org/wiki/Functional_testing">functional testing</a>. I wanted to execute an application and apply some assertions on the output of the software(basically running a console app, parse the xml output and assert on values in the output).
<blockquote>FYI: I’m very new to PowerShell, so any suggestions on how I implemented the below are welcome…</blockquote>
I’ve seen a couple examples of writing test assertions in PowerShell out there. One example is <a href="http://www.psunit.org/">PSUnit</a>; however, this seemed a little heavy for my needs and not quite the syntactic sugar I was looking for.

Besides the syntax flavor I was desiring, another thing I wanted to do was leverage the power of NUnit.Framework’s assertion capabilities. I like the error messages generated when strings and other objects fail the assertion.
<h5>Examples of end result ShouldLookLike()…</h5>
$true.ShouldBeTrue()
$false.ShouldBeFalse()
"a".ShouldEqual("a")
"a".ShouldNotEqual("b")
<h5><strong>Step 1</strong>: Figure out how to write a C# style <a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx">extension method</a> in PowerShell.</h5>
<blockquote>I found a great blog post describing how to extend any PowerShell object to add extension methods.

<a href="http://bartdesmet.net/blogs/bart/archive/2007/09/06/extension-methods-in-windows-powershell.aspx">Extension Methods in Windows PowerShell</a></blockquote>
In short, to extend types in PowerShell leveraging the <a href="http://msdn.microsoft.com/en-us/library/ms714419(VS.85).aspx">Extended Type System</a>, you need to define them in an xml file and import the method definitions into the PowerShell runtime instance.

Below is PowerShell XML definition for my NUnit Specification Extensions.
<pre class="brush: xml;">&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;Types&gt;
    &lt;Type&gt;
        &lt;Name&gt;System.Object&lt;/Name&gt;
        &lt;Members&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeFalse&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsFalse($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeTrue&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsTrue($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldNotEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreNotEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
        &lt;/Members&gt;
    &lt;/Type&gt;
&lt;/Types&gt;</pre>
<h4></h4>
Take the above XML and save it to a file…
<blockquote>NOTE: the file HAS to be saved with the extension <strong>.ps1xml</strong>

Ex: NunitSpecificationPowerShellExtensions<strong>.ps1xml</strong></blockquote>
<h4></h4>
<h5>Step 2: Load the extended type definition into the PowerShell runtime.</h5>
Once you’ve saved the XML extended types to a file, you need to load it into the PowerShell runtime by executing the command below.
<blockquote>
Update-TypeData -PrependPath NunitSpecificationPowerShellExtensions.ps1xml</blockquote>
Before executing the above statement…Let’s quickly look at a System.String’s members and properties – just to show you what the extension methods look like when applied inside of the runtime.<a href="http://elegantcode.com/wp-content/uploads/2009/10/image3.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb2.png" border="0" alt="image" width="586" height="479" /></a>

After executing the Update-TypeData command you’ll notice there are a number of “ScriptMethod” MemberTypes added to the object.

<a href="http://elegantcode.com/wp-content/uploads/2009/10/image4.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb3.png" border="0" alt="image" width="600" height="580" /></a>

Now if you try to execute one of those newly added extension methods, you may get the following error…

PS C:\&gt; $testVar.<strong>ShouldEqual</strong>("hello world")

Exception calling "ShouldEqual" with "1" argument(s): "<strong>Unable to find type [NUnit.Framework.Assert]: make sure that the

assembly containing this type is loaded.</strong>"

At line:1 char:21

+ $testVar.ShouldEqual &lt;&lt;&lt;&lt; ("hello world")

+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

+ FullyQualifiedErrorId : ScriptMethodRuntimeException

This is because we need to load the NUnit.Framework assembly into the runtime before we can leverage the extension methods.
<blockquote>[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null</blockquote>
Now that the extension methods have been defined and loaded into the runtime, NUnit.Framework is loaded, we can now use the methods on any object that inherits from System.Object (which, as far as I know, is everything in PowerShell).

And now, everything you need in one script (if you have the xml extended type file saved somewhere…)
<pre>#
# Update-TypeData -prependPath C:\Code\NunitSpecificationPowerShellExtensions.ps1xml
#

[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null

$true.ShouldBeTrue()

$false.ShouldBeFalse()

"a".ShouldEqual("a")

"a".ShouldNotEqual("b")</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>PowerShell Management Library for Hyper-V</title>
		<link>http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-management-library-for-hyper-v</link>
		<comments>http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/#comments</comments>
		<pubDate>Wed, 25 Mar 2009 21:46:16 +0000</pubDate>
		<dc:creator>Alex Mueller</dc:creator>
				<category><![CDATA[Hyper-V]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Tools and Utilities]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/</guid>
		<description><![CDATA[I am always looking for tools to allow me to do more by doing less. Administering Hyper-V with PowerShell can be tedious. James O’Neill’s PowerShell Management Library for Hyper-V is a great tool to improve automation of Hyper-V management using PowerShell. As a tester, I am constantly creating new environments, installing our product, taking snapshots, [...]]]></description>
			<content:encoded><![CDATA[<p>I am always looking for tools to allow me to do more by doing less. Administering Hyper-V with PowerShell can be tedious. James O’Neill’s <a href="http://pshyperv.codeplex.com/" target="_blank">PowerShell Management Library for Hyper-V</a> is a great tool to improve automation of Hyper-V management using PowerShell.</p>  <p>As a tester, I am constantly creating new environments, installing our product, taking snapshots, ect. Doing this by hand is a waste of time in my opinion. Doing this with a script makes life easier and frees up my time. </p>  <p>Typically, I prefer to create is to create one VM and to have other VMs inherit from that base image. My second VM (the first child to inherit from the base), I will install daily builds of our product. I will then create a third child, which I use a sandbox. I can easily delete it and recreate as needed without having to install our product over again. I have not consistently found success with using snapshots, so I prefer to use differencing disks. The examples below use differencing disks. </p>  <p>This first code block shows how I am using the PowerShell management library to simply the creation of a base VM. There is nothing magic about it. It’s pretty strait-forward. I create a VM, give it a name, set the CPU count, memory size, network adapters, hard drive, and DVD drive.</p>  <pre class="code"><span style="color: purple">$server </span><span style="color: red">= </span><span style="color: maroon">&quot;my-dev-server&quot;
</span><span style="color: purple">$vmName </span><span style="color: red">= </span><span style="color: maroon">&quot;TestParentVM&quot;
</span><span style="color: purple">$vmVirtualSwitch </span><span style="color: red">= </span><span style="color: maroon">&quot;My Virtual Network&quot;

</span><span style="color: green"># create a new virtual machine
</span><span style="color: purple">$vm </span><span style="color: red">= </span><span style="color: black">New-VM </span><span style="color: purple">$vmName </span><span style="color: black">-server </span><span style="color: purple">$server

</span><span style="color: green"># set cpu count
</span><span style="color: black">Set-VMCPUCount </span><span style="color: purple">$vm </span><span style="color: black">2 -server </span><span style="color: purple">$server

</span><span style="color: green"># set memory size
</span><span style="color: black">Set-VMMemory </span><span style="color: purple">$vm </span><span style="color: black">2 -memory 4GB -server </span><span style="color: purple">$server

</span><span style="color: green"># add a legacy network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch </span><span style="color: black">-legacy

</span><span style="color: green"># add a default VMBus (non-legacy) network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch

</span><span style="color: green"># add the hard drive to the VM
</span><span style="color: black">Add-VMNewHardDisk –vm </span><span style="color: purple">$vm </span><span style="color: black">-controllerID 0 -lun 0 -vhdpath </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmName.vhd&quot; </span><span style="color: black">-size 20GB

</span><span style="color: green"># add the DVD with bootup ISO
</span><span style="color: black">Add-VMDRIVE –vm </span><span style="color: purple">$vm </span><span style="color: black">1 1 -server </span><span style="color: purple">$server </span><span style="color: black">-DVD 

</span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;Operation complete.&quot;</span></pre>
<a href="http://11011.net/software/vspaste"></a>

<p>The next code block will create a differencing disk pointing to the parent created in the previous example. I create the usual, VM, CPU count, ect. What makes this a differencing disk is how the VHD is created by specifying the parent. I do some cleanup in this routine by deleting any previously created VMs or VHDs, and I loop through the creation a failure preventative. </p>

<pre class="code"><span style="color: purple">$server </span><span style="color: red">= </span><span style="color: maroon">&quot;my-dev-server&quot;
</span><span style="color: purple">$vmName </span><span style="color: red">= </span><span style="color: maroon">&quot;TestChildVM&quot;
</span><span style="color: purple">$vmParent </span><span style="color: red">= </span><span style="color: maroon">&quot;TestParentVM&quot;
</span><span style="color: purple">$vmVirtualSwitch </span><span style="color: red">= </span><span style="color: maroon">&quot;My Virtual Network&quot;

</span><span style="color: blue">#region </span><span style="color: black">functions - feel free to move to a separate file

</span><span style="color: blue">Function </span><span style="color: #5f9ea0">DeleteVhd
</span><span style="color: black">{
    </span><span style="color: blue">Param </span><span style="color: black">(</span><span style="color: purple">$pathToVhd</span><span style="color: black">)
    </span><span style="color: green"># delete the disk that was added if it exists
    </span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: #5f9ea0">test-path -path </span><span style="color: purple">$pathToVhd</span><span style="color: black">)
    {
        </span><span style="color: #5f9ea0">Remove-Item -Path </span><span style="color: purple">$pathToVhd </span><span style="color: #5f9ea0">-Force
    </span><span style="color: black">}
}

</span><span style="color: blue">#endregion

</span><span style="color: green"># delete the VHD if it already exists
</span><span style="color: #5f9ea0">DeleteVhd </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmName.vhd&quot;

</span><span style="color: green"># delete the VM if it already exists
</span><span style="color: black">Remove-VM -vm </span><span style="color: purple">$vmName </span><span style="color: black">-server </span><span style="color: purple">$server

</span><span style="color: green"># create a new virtual machine
</span><span style="color: purple">$vm </span><span style="color: red">= </span><span style="color: black">New-VM </span><span style="color: purple">$vmName </span><span style="color: black">-server </span><span style="color: purple">$server

</span><span style="color: green"># get the vm
</span><span style="color: purple">$vm </span><span style="color: red">= </span><span style="color: black">Get-VM </span><span style="color: purple">$vmName

</span><span style="color: green"># set cpu count
</span><span style="color: black">Set-VMCPUCount </span><span style="color: purple">$vm </span><span style="color: black">2 -server </span><span style="color: purple">$server

</span><span style="color: green"># set memory size
</span><span style="color: black">Set-VMMemory </span><span style="color: purple">$vm </span><span style="color: black">2 -memory 4GB -server </span><span style="color: purple">$server

</span><span style="color: green"># get VM Nics available
</span><span style="color: purple">$vmNics </span><span style="color: red">= </span><span style="color: black">Get-VMNic -server </span><span style="color: purple">$server </span><span style="color: black">-vmbus -legacy
</span><span style="color: purple">$vmNicSwitchList </span><span style="color: red">= </span><span style="color: #5f9ea0">New-Object </span><span style="color: maroon">System.Collections.ArrayList

</span><span style="color: green"># get VM Nic Switch available for each VM Nic and add it to our list
</span><span style="color: blue">foreach </span><span style="color: black">(</span><span style="color: purple">$vmNic </span><span style="color: blue">in </span><span style="color: purple">$vmNics</span><span style="color: black">)
{
    </span><span style="color: purple">$vmSwitchElementName </span><span style="color: red">= </span><span style="color: black">(Get-VMNicSwitch </span><span style="color: purple">$vmNic</span><span style="color: black">).ElementName
    </span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">.Contains(</span><span style="color: purple">$vmSwitchElementName</span><span style="color: black">) </span><span style="color: red">-ne </span><span style="color: blue">$true</span><span style="color: black">)
    {
        </span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">.Add(</span><span style="color: purple">$vmSwitchElementName</span><span style="color: black">)
    }
}

</span><span style="color: green"># Use the first available VM Nic Switch - this assumes 
# I do not create more than on per each environment.
</span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">.Count </span><span style="color: red">-gt </span><span style="color: black">0)
{
    </span><span style="color: purple">$vmVirtualSwitch </span><span style="color: red">= </span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">[0]
}

</span><span style="color: green"># add a legacy network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch </span><span style="color: black">-legacy

</span><span style="color: green"># add a default VMBus (non-legacy) network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch

</span><span style="color: green"># add the hard drive to the VM
</span><span style="color: purple">$parent </span><span style="color: red">= </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmParent.vhd&quot;
</span><span style="color: purple">$vhdPath </span><span style="color: red">= </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmName.vhd&quot;
</span><span style="color: black">Add-VMNewHardDisk –vm </span><span style="color: purple">$vm </span><span style="color: black">-controllerID 0 -lun 0 -vhdpath </span><span style="color: purple">$vhdPath </span><span style="color: black">-parent </span><span style="color: purple">$parent

</span><span style="color: green"># get the VM to see if a disk is attached to it, if it is not, then it failed
</span><span style="color: purple">$disks </span><span style="color: red">= </span><span style="color: black">Get-VMDisk -vm </span><span style="color: purple">$vm
$count </span><span style="color: red">= </span><span style="color: black">1

</span><span style="color: green"># if the disk was not successfully added, try and add it again
</span><span style="color: blue">while </span><span style="color: black">(</span><span style="color: purple">$disks </span><span style="color: red">-eq </span><span style="color: purple">$null </span><span style="color: red">-and </span><span style="color: purple">$count </span><span style="color: red">-le </span><span style="color: black">5)
{
    </span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;RETRY $count - The disk was not properly added. Attempting to retry.&quot;
    
    </span><span style="color: green"># delete the disk that was added
    </span><span style="color: #5f9ea0">DeleteVhd </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmName.vhd&quot;
    
    </span><span style="color: black">Add-VMNewHardDisk –vm </span><span style="color: purple">$vm </span><span style="color: black">-controllerID 0 -lun 0 -vhdpath </span><span style="color: purple">$vhdPath </span><span style="color: black">-parent </span><span style="color: purple">$parent
    
    $disks </span><span style="color: red">= </span><span style="color: black">Get-VMDisk -vm </span><span style="color: purple">$vm
    $count</span><span style="color: red">++
</span><span style="color: black">}

</span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: purple">$disks </span><span style="color: red">-eq </span><span style="color: purple">$null</span><span style="color: black">)
{
    </span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;Operation failed to create this virtual machine. Contact an admin.&quot;
</span><span style="color: black">}
</span><span style="color: blue">else
</span><span style="color: black">{
    </span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;Operation completed successfully. Attempting to start the VM.&quot;
    </span><span style="color: black">Start-VM -vm </span><span style="color: purple">$vm </span><span style="color: black">-wait
}</span></pre>
<a href="http://11011.net/software/vspaste"></a>

<p>I have found that the VM creation is not consistently successful on the first pass, so I have added the while loop. Since adding that, I have not had any issues.</p>

<p>I hope these help. They should be easy to change if you prefer snapshots versus differencing disks. Thanks to James O’Neill for creating this library. It makes administering Hyper-V much easier. It is available via <a title="CodePlex" href="http://www.codeplex.com/" target="_blank">CodePlex</a>, where the latest release, updates, and forum support can be found. </p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Installing Windows 7</title>
		<link>http://elegantcode.com/2009/02/09/installing-windows-7/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=installing-windows-7</link>
		<comments>http://elegantcode.com/2009/02/09/installing-windows-7/#comments</comments>
		<pubDate>Mon, 09 Feb 2009 21:14:36 +0000</pubDate>
		<dc:creator>Alex Mueller</dc:creator>
				<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Operating Systems]]></category>
		<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/02/09/installing-windows-7/</guid>
		<description><![CDATA[The short story is this. If you are accessing Windows 7 from your MSDN subscriptions, save yourself time and frustration by installing the Windows 7 Beta, not the Windows 7 Beta Checked Build. See available downloads here. This past weekend, I decided to upgrade my work laptop from Vista Enterprise to Windows 7 Ultimate Beta. [...]]]></description>
			<content:encoded><![CDATA[<p>The short story is this. If you are accessing Windows 7 from your MSDN subscriptions, save yourself time and frustration by installing the Windows 7 Beta, not the Windows 7 Beta Checked Build. <a href="http://msdn.microsoft.com/en-us/subscriptions/cc137115.aspx" target="_blank">See available downloads here</a>.</p>  <p>This past weekend, I decided to upgrade my work laptop from Vista Enterprise to Windows 7 Ultimate Beta. I was unable to upgrade from Vista Enterprise to 7 Ultimate because that action is not supported. I then tried to upgrade from Enterprise to 7 Enterprise, but I was unable to upgrade from a staged build to a non-staged build. I decided to repave entirely, choosing Windows 7 Ultimate Beta, and I tried to do all of this on a Friday afternoon, two hours before leaving.</p>  <p>I installed Windows 7 Beta Checked Build (x86) - DVD (English), last updated on January 14, 2009,&#160; from my MSDN subscription. I did not install an internal build. Instead, I decided to go with what is publicly available via MSDN. </p>  <p>Why did I go with a <a href="http://msdn.microsoft.com/en-us/library/ms792442.aspx" target="_blank">Checked Build</a>? Because I failed to read the details describing it. What it cost me in time and frustration, I gain in valuable learning experiences. So it was not a total loss. I received a number of buggy issues with the checked build, mainly the inability for Windows Update to properly download all of my necessary updates, including my video drivers and smart card reader, where the latter enables me to remotely access my work domain. </p>  <p>I gave up and decided to download and install the Windows 7 Beta – DVD (English). Everything works great. I was able to get online, download all of my updates, and connect to my work domain. No issues found so far, and no annoying assertion error popups. </p>  <p>My favorite Windows 7 feature so far (non-UI related) is that PowerShell 2.0 is installed by default. PowerShell 2.0 provides more functionality for remoting, among other enhancements.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/02/09/installing-windows-7/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>PowerShell Documentation</title>
		<link>http://elegantcode.com/2008/12/17/powershell-documentation/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-documentation</link>
		<comments>http://elegantcode.com/2008/12/17/powershell-documentation/#comments</comments>
		<pubDate>Wed, 17 Dec 2008 20:36:54 +0000</pubDate>
		<dc:creator>Alex Mueller</dc:creator>
				<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/12/17/powershell-documentation/</guid>
		<description><![CDATA[PowerShell documentation, you are too honest. Get-Help Remove-Item -Full As I was retrieving information on "Remove-Item," this is what I came across. There is more detail beyond what I am showing, but pay attention to what is bolded. NAME&#160;&#160;&#160; Remove-Item SYNOPSIS&#160;&#160;&#160; Deletes the specified items. SYNTAX&#160;&#160;&#160; Remove-Item [-path] &#60;string[]&#62; [-recurse] [-force] [-include &#60;string[]&#62;] [-&#160;&#160;&#160; exclude [...]]]></description>
			<content:encoded><![CDATA[<p>PowerShell documentation, you are too honest. </p> <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:F2210F5F-69EB-4d4c-AFF7-B8A050E9CC72:2ed0ad7a-f3da-498d-a817-1bb0c8b8f8c3" class="wlWriterSmartContent"><pre  style="width:100%;;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #000000;">Get</span><span style="color: #000000;">-</span><span style="color: #000000;">Help Remove</span><span style="color: #000000;">-</span><span style="color: #000000;">Item </span><span style="color: #000000;">-</span><span style="color: #000000;">Full</span></div></pre></div>
<p>As I was retrieving information on "Remove-Item," this is what I came across. There is more detail beyond what I am showing, but pay attention to what is <strong>bolded</strong>. </p>
<blockquote>
<p>NAME<br>&nbsp;&nbsp;&nbsp; Remove-Item 
<p>SYNOPSIS<br>&nbsp;&nbsp;&nbsp; Deletes the specified items. 
<p>SYNTAX<br>&nbsp;&nbsp;&nbsp; Remove-Item [-path] &lt;string[]&gt; [-recurse] [-force] [-include &lt;string[]&gt;] [-<br>&nbsp;&nbsp;&nbsp; exclude &lt;string[]&gt;] [-filter &lt;string&gt;] [-credential &lt;PSCredential&gt;] [-whatI<br>&nbsp;&nbsp;&nbsp; f] [-confirm] [&lt;CommonParameters&gt;] 
<p>&nbsp;&nbsp;&nbsp; Remove-Item [-literalPath] &lt;string[]&gt; [-recurse] [-force] [-include &lt;string<br>&nbsp;&nbsp;&nbsp; []&gt;] [-exclude &lt;string[]&gt;] [-filter &lt;string&gt;] [-credential &lt;PSCredential&gt;]<br>&nbsp;&nbsp;&nbsp; [-whatIf] [-confirm] [&lt;CommonParameters&gt;] 
<p>DETAILED DESCRIPTION<br>&nbsp;&nbsp;&nbsp; The Remove-Item cmdlet deletes one or more items. Because it is supported b<br>&nbsp;&nbsp;&nbsp; y many providers, it can delete many different types of items, including fi<br>&nbsp;&nbsp;&nbsp; les, directories, registry keys, variables, aliases, certificates, and func<br>&nbsp;&nbsp;&nbsp; tions. 
<p>PARAMETERS<br>&nbsp;&nbsp;&nbsp; -path &lt;string[]&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Specifies a path to the items being removed. Wildcards are permitted. T<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; he parameter name ("-Path") is optional. 
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Required?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; true<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Position?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 1<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Default value&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; N/A - The path must be specified<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept pipeline input?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; true (ByValue, ByPropertyName)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept wildcard characters?&nbsp; true 
<p>&nbsp;&nbsp;&nbsp; -recurse &lt;SwitchParameter&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Deletes the items in the specified locations and in all child items of<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; the locations. 
<p><strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; The Recurse parameter in this cmdlet does not work properly. </strong>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Required?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; false<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Position?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; named<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Default value&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; False<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept pipeline input?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; false<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept wildcard characters?&nbsp; false 
<p><strong></strong>&nbsp;</p></blockquote>
<p>"Hmmm... Am I feeling lucky? Ahhh, what the hell, let's do it."</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:F2210F5F-69EB-4d4c-AFF7-B8A050E9CC72:a3ee0edf-63f8-43fc-a4fb-22c6277656f8" class="wlWriterSmartContent"><pre  style="width:100%;;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #000000;">Remove</span><span style="color: #000000;">-</span><span style="color: #000000;">Item </span><span style="color: #800000;">&quot;</span><span style="color: #800000;">C:\</span><span style="color: #800000;">&quot;</span><span style="color: #000000;"> </span><span style="color: #000000;">-</span><span style="color: #000000;">Recurse</span></div></pre></div>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/12/17/powershell-documentation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Automate Daily Tasks with PowerShell</title>
		<link>http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-load-assembly-without-locking-file</link>
		<comments>http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/#comments</comments>
		<pubDate>Wed, 23 Dec 2009 05:40:23 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/</guid>
		<description><![CDATA[I have a set of PowerShell build scripts and ran into a case where I needed to load an assembly (to get the assembly’s version) and still (at a later time) work with the assembly file on disk. A typical way to load an assembly within PowerShell is to use the Assembly.LoadFrom(filePath) # Powershell [System.Reflection.Assembly]::LoadFrom($assemblyPath) [...]]]></description>
			<content:encoded><![CDATA[<p>I have a set of PowerShell build scripts and ran into a case where I needed to load an assembly (to get the assembly’s version) and still (at a later time) work with the assembly file on disk.</p>  <p>A typical way to load an assembly within PowerShell is to use the Assembly.LoadFrom(filePath)</p>  <blockquote>   <p># Powershell</p>    <p>[System.Reflection.Assembly]::LoadFrom($assemblyPath)</p> </blockquote>  <p><a href="http://elegantcode.com/wp-content/uploads/2009/12/image9.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://elegantcode.com/wp-content/uploads/2009/12/image_thumb9.png" width="690" height="391" /></a> </p>  <p>Except the problem with this (in my case) was it would <strong>lock the file for the lifespan of the PowerShell console instance</strong>. I didn’t want to have to close and re-open the PowerShell console every time I need to run a build so there had to be a work-around for this.</p>  <p>After searching the web for a solution, I couldn’t find anything that was “easy” and worth the effort to get it to work.</p>  <blockquote>   <p>EX: One solution was to create a new AppDomain, do the necessary work and the close the AppDomain which would release the lock on the file.</p>    <p>I’ve never done this myself, and even thought there is example code out there to get this accomplished, it just seemed over the top for what I was trying to do, and back to my previous criteria it wasn’t “worth the effort to get it to work”</p> </blockquote>  <p>Then I remembered in a previous life I used an overload that took an array of bytes to load the an assembly.</p>  <blockquote>   <p>[System.Reflection.Assembly]::Load($assemblyBytes)</p> </blockquote>  <p>After spiking it in PowerShell with the below test. I was quite happy with the solution, so I thought I’d throw it out there.</p>  <p>Just stream the assembly from disk into a byte array manually, and call assembly load from there.</p>  <p>Here’s my test case which shows that the file is not locked after it was loaded into the PowerShell runtime</p>  <pre>$file = &quot;.\Moq.dll&quot;
$tempFileName = &quot;.\Moq-Renamed.dll&quot;

$fileStream = ([System.IO.FileInfo] (Get-Item $file)).OpenRead();
$assemblyBytes = new-object byte[] $fileStream.Length
$fileStream.Read($assemblyBytes, 0, $fileStream.Length);
$fileStream.Close();

$assemblyLoaded = [System.Reflection.Assembly]::Load($assemblyBytes);

# notice that we can move the file on disk after 
# it's loaded into the powershell runtime
Move-Item $file $tempFileName
Move-Item $tempFileName $file 

# and display the assembly information to show we still have it in memory
echo $assemblyLoaded</pre>

<p>After that test passed, and the main reason I wanted to do this, I wrote the “get-assembly-version” PowerShell function.</p>

<pre><strike>function get-assembly-version() {
    param([string] $file)
    
    # load the assembly bytes quickly - as to not lock the file for too long
    $fileStream = ([System.IO.FileInfo] (Get-Item $file)).OpenRead()
    $assemblyBytes = new-object byte[] $fileStream.Length
    $fileStream.Read($assemblyBytes, 0, $fileStream.Length) | Out-Null #out null this because this function should only return the version &amp; this call was outputting some garbage number
    $fileStream.Close()
    
    # return the version of the assembly
    [System.Reflection.Assembly]::Load($assemblyBytes).GetName().Version;
}

$version = get-assembly-version(&quot;.\Moq.dll&quot;)

echo &quot;Loaded v$($version.Major).$($version.Minor).$($version.Build).$($version.Revision) version of $file&quot;</strike></pre>
Hope this helps someone out there! 

<p></p>

<p>&#160;</p>

<p><strong>UPDATE:</strong></p>

<p><a href="http://achuebrigens.wordpress.com">Martin</a> commented below on a much better solution to the assembly version info problem. Amazing how complicated we can make things if we don’t know the path.</p>

<pre>
function get-assembly-version() {
    param([string] $file)
    
    $version = [System.Reflection.AssemblyName]::GetAssemblyName($file).Version;
    
    #format the version and output it...
    $version
}</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Elegant Code &#187; PowerShell</title>
	<atom:link href="http://elegantcode.com/category/microsoft/powershell/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Silverlight Profiling PowerShell helper.</title>
		<link>http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=silverlight-profiling-powershell-helper</link>
		<comments>http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/#comments</comments>
		<pubDate>Sat, 15 May 2010 16:47:22 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/</guid>
		<description><![CDATA[I was playing around with some Silverlight profiling the other night to see if I could find any obvious issues with my open source project StatLight and wound up writing a little script in PowerShell I hoped someone might find helpful. But I didn’t know you could profile a Silverlight app. I didn’t until I [...]]]></description>
			<content:encoded><![CDATA[<p>I was playing around with some Silverlight profiling the other night to see if I could find any obvious issues with my open source project <a href="http://statlight.net" target="_blank">StatLight</a> and wound up writing a little script in PowerShell I hoped someone might find helpful.</p>  <h4>But I didn’t know you could profile a Silverlight app.</h4>  <p>I didn’t until I started doing some digging online. Now, the Silverlight profiling story (at least from what I’ve seen/tried) is not near the easy of say <a href="http://www.red-gate.com/products/ants_performance_profiler/index.htm">Redgate ANTS Performance Profiler</a>. However, it’s do-able. (And with this helper script – hopefully a little simpler?)</p>  <h4>How can I profile a Silverlight Application?</h4>  <p>I would recommend you read the following blog, which explains one way of doing it very well.</p>  <p><a title="http://blogs.msdn.com/profiler/archive/2010/04/26/vs2010-silverlight-4-profiling.aspx" href="http://blogs.msdn.com/profiler/archive/2010/04/26/vs2010-silverlight-4-profiling.aspx">http://blogs.msdn.com/profiler/archive/2010/04/26/vs2010-silverlight-4-profiling.aspx</a></p>  <h4>So… what’s this script for?</h4>  <p>If you read the blog above, or have done this before, then you probably noticed that there was quite a series of commands you had to execute before you could wind up with a performance report. </p>  <p>I threw together a quick little PowerShell script in an attempt to automate smooth out the process.</p>  <h4>Hot do I use it?</h4>  <ol>   <li>Download the script &amp; save it somewhere. <a href="http://github.com/staxmanade/Scripts/blob/master/SilverlightProfiler.ps1"><strong>http://github.com/staxmanade/Scripts/blob/master/SilverlightProfiler.ps1</strong></a> </li>    <li>Open the PowerShell console. cd to the directory your xap/assemblies are stored.      <br />(EX: {myProject}\Bin\Debug\ ) </li>    <li>Execute:      <br />{pathToScript}\SilverlightProfiler.ps1 -urlPath &quot;{myProject}\Bin\Debug\TestPage.html&quot; </li>    <li>When your done profiling press enter to signal that your done.      <p></p> Once complete, it will print the location your profiling report was saved. You can then open it with Visual Studio.</li> </ol>  <h5>Couple of disclaimers.</h5>  <ul>   <li>Some paths are hard-coded to my x86 machine. </li>    <li>I had troubles running the built in visual studio .bat files (from powershell) that are supposed to set the environment variables. So I extracted out what vars I could find to make it work. </li>    <li>I’m not a profiling expert – just hacked this together to get it to work for me.</li> </ul>  <p>I hope this is useful, and if you know of a better way, I’m always interested in hearing your feedback.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Powershell: Load assembly without locking file.</title>
		<link>http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-load-assembly-without-locking-file</link>
		<comments>http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/#comments</comments>
		<pubDate>Wed, 23 Dec 2009 05:40:23 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/</guid>
		<description><![CDATA[I have a set of PowerShell build scripts and ran into a case where I needed to load an assembly (to get the assembly’s version) and still (at a later time) work with the assembly file on disk. A typical way to load an assembly within PowerShell is to use the Assembly.LoadFrom(filePath) # Powershell [System.Reflection.Assembly]::LoadFrom($assemblyPath) [...]]]></description>
			<content:encoded><![CDATA[<p>I have a set of PowerShell build scripts and ran into a case where I needed to load an assembly (to get the assembly’s version) and still (at a later time) work with the assembly file on disk.</p>  <p>A typical way to load an assembly within PowerShell is to use the Assembly.LoadFrom(filePath)</p>  <blockquote>   <p># Powershell</p>    <p>[System.Reflection.Assembly]::LoadFrom($assemblyPath)</p> </blockquote>  <p><a href="http://elegantcode.com/wp-content/uploads/2009/12/image9.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://elegantcode.com/wp-content/uploads/2009/12/image_thumb9.png" width="690" height="391" /></a> </p>  <p>Except the problem with this (in my case) was it would <strong>lock the file for the lifespan of the PowerShell console instance</strong>. I didn’t want to have to close and re-open the PowerShell console every time I need to run a build so there had to be a work-around for this.</p>  <p>After searching the web for a solution, I couldn’t find anything that was “easy” and worth the effort to get it to work.</p>  <blockquote>   <p>EX: One solution was to create a new AppDomain, do the necessary work and the close the AppDomain which would release the lock on the file.</p>    <p>I’ve never done this myself, and even thought there is example code out there to get this accomplished, it just seemed over the top for what I was trying to do, and back to my previous criteria it wasn’t “worth the effort to get it to work”</p> </blockquote>  <p>Then I remembered in a previous life I used an overload that took an array of bytes to load the an assembly.</p>  <blockquote>   <p>[System.Reflection.Assembly]::Load($assemblyBytes)</p> </blockquote>  <p>After spiking it in PowerShell with the below test. I was quite happy with the solution, so I thought I’d throw it out there.</p>  <p>Just stream the assembly from disk into a byte array manually, and call assembly load from there.</p>  <p>Here’s my test case which shows that the file is not locked after it was loaded into the PowerShell runtime</p>  <pre>$file = &quot;.\Moq.dll&quot;
$tempFileName = &quot;.\Moq-Renamed.dll&quot;

$fileStream = ([System.IO.FileInfo] (Get-Item $file)).OpenRead();
$assemblyBytes = new-object byte[] $fileStream.Length
$fileStream.Read($assemblyBytes, 0, $fileStream.Length);
$fileStream.Close();

$assemblyLoaded = [System.Reflection.Assembly]::Load($assemblyBytes);

# notice that we can move the file on disk after 
# it's loaded into the powershell runtime
Move-Item $file $tempFileName
Move-Item $tempFileName $file 

# and display the assembly information to show we still have it in memory
echo $assemblyLoaded</pre>

<p>After that test passed, and the main reason I wanted to do this, I wrote the “get-assembly-version” PowerShell function.</p>

<pre><strike>function get-assembly-version() {
    param([string] $file)
    
    # load the assembly bytes quickly - as to not lock the file for too long
    $fileStream = ([System.IO.FileInfo] (Get-Item $file)).OpenRead()
    $assemblyBytes = new-object byte[] $fileStream.Length
    $fileStream.Read($assemblyBytes, 0, $fileStream.Length) | Out-Null #out null this because this function should only return the version &amp; this call was outputting some garbage number
    $fileStream.Close()
    
    # return the version of the assembly
    [System.Reflection.Assembly]::Load($assemblyBytes).GetName().Version;
}

$version = get-assembly-version(&quot;.\Moq.dll&quot;)

echo &quot;Loaded v$($version.Major).$($version.Minor).$($version.Build).$($version.Revision) version of $file&quot;</strike></pre>
Hope this helps someone out there! 

<p></p>

<p>&#160;</p>

<p><strong>UPDATE:</strong></p>

<p><a href="http://achuebrigens.wordpress.com">Martin</a> commented below on a much better solution to the assembly version info problem. Amazing how complicated we can make things if we don’t know the path.</p>

<pre>
function get-assembly-version() {
    param([string] $file)
    
    $version = [System.Reflection.AssemblyName]::GetAssemblyName($file).Version;
    
    #format the version and output it...
    $version
}</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Integration Test Brought to you by Powershell &amp; NUnit &#8211; with a Little Specification Syntax for Flavoring</title>
		<link>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring</link>
		<comments>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/#comments</comments>
		<pubDate>Mon, 26 Oct 2009 05:00:40 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/</guid>
		<description><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about Fluent Specification Extensions in a past blog. Recently I wanted to execute a PowerShell script [...]]]></description>
			<content:encoded><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about <a href="http://staxmanade.blogspot.com/2009/02/fluent-specification-extensions.html">Fluent Specification Extensions</a> in a past blog.

Recently I wanted to execute a PowerShell script to do some automated <a href="http://en.wikipedia.org/wiki/Functional_testing">functional testing</a>. I wanted to execute an application and apply some assertions on the output of the software(basically running a console app, parse the xml output and assert on values in the output).
<blockquote>FYI: I’m very new to PowerShell, so any suggestions on how I implemented the below are welcome…</blockquote>
I’ve seen a couple examples of writing test assertions in PowerShell out there. One example is <a href="http://www.psunit.org/">PSUnit</a>; however, this seemed a little heavy for my needs and not quite the syntactic sugar I was looking for.

Besides the syntax flavor I was desiring, another thing I wanted to do was leverage the power of NUnit.Framework’s assertion capabilities. I like the error messages generated when strings and other objects fail the assertion.
<h5>Examples of end result ShouldLookLike()…</h5>
$true.ShouldBeTrue()
$false.ShouldBeFalse()
"a".ShouldEqual("a")
"a".ShouldNotEqual("b")
<h5><strong>Step 1</strong>: Figure out how to write a C# style <a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx">extension method</a> in PowerShell.</h5>
<blockquote>I found a great blog post describing how to extend any PowerShell object to add extension methods.

<a href="http://bartdesmet.net/blogs/bart/archive/2007/09/06/extension-methods-in-windows-powershell.aspx">Extension Methods in Windows PowerShell</a></blockquote>
In short, to extend types in PowerShell leveraging the <a href="http://msdn.microsoft.com/en-us/library/ms714419(VS.85).aspx">Extended Type System</a>, you need to define them in an xml file and import the method definitions into the PowerShell runtime instance.

Below is PowerShell XML definition for my NUnit Specification Extensions.
<pre class="brush: xml;">&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;Types&gt;
    &lt;Type&gt;
        &lt;Name&gt;System.Object&lt;/Name&gt;
        &lt;Members&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeFalse&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsFalse($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeTrue&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsTrue($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldNotEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreNotEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
        &lt;/Members&gt;
    &lt;/Type&gt;
&lt;/Types&gt;</pre>
<h4></h4>
Take the above XML and save it to a file…
<blockquote>NOTE: the file HAS to be saved with the extension <strong>.ps1xml</strong>

Ex: NunitSpecificationPowerShellExtensions<strong>.ps1xml</strong></blockquote>
<h4></h4>
<h5>Step 2: Load the extended type definition into the PowerShell runtime.</h5>
Once you’ve saved the XML extended types to a file, you need to load it into the PowerShell runtime by executing the command below.
<blockquote>
Update-TypeData -PrependPath NunitSpecificationPowerShellExtensions.ps1xml</blockquote>
Before executing the above statement…Let’s quickly look at a System.String’s members and properties – just to show you what the extension methods look like when applied inside of the runtime.<a href="http://elegantcode.com/wp-content/uploads/2009/10/image3.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb2.png" border="0" alt="image" width="586" height="479" /></a>

After executing the Update-TypeData command you’ll notice there are a number of “ScriptMethod” MemberTypes added to the object.

<a href="http://elegantcode.com/wp-content/uploads/2009/10/image4.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb3.png" border="0" alt="image" width="600" height="580" /></a>

Now if you try to execute one of those newly added extension methods, you may get the following error…

PS C:\&gt; $testVar.<strong>ShouldEqual</strong>("hello world")

Exception calling "ShouldEqual" with "1" argument(s): "<strong>Unable to find type [NUnit.Framework.Assert]: make sure that the

assembly containing this type is loaded.</strong>"

At line:1 char:21

+ $testVar.ShouldEqual &lt;&lt;&lt;&lt; ("hello world")

+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

+ FullyQualifiedErrorId : ScriptMethodRuntimeException

This is because we need to load the NUnit.Framework assembly into the runtime before we can leverage the extension methods.
<blockquote>[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null</blockquote>
Now that the extension methods have been defined and loaded into the runtime, NUnit.Framework is loaded, we can now use the methods on any object that inherits from System.Object (which, as far as I know, is everything in PowerShell).

And now, everything you need in one script (if you have the xml extended type file saved somewhere…)
<pre>#
# Update-TypeData -prependPath C:\Code\NunitSpecificationPowerShellExtensions.ps1xml
#

[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null

$true.ShouldBeTrue()

$false.ShouldBeFalse()

"a".ShouldEqual("a")

"a".ShouldNotEqual("b")</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>PowerShell Management Library for Hyper-V</title>
		<link>http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-management-library-for-hyper-v</link>
		<comments>http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/#comments</comments>
		<pubDate>Wed, 25 Mar 2009 21:46:16 +0000</pubDate>
		<dc:creator>Alex Mueller</dc:creator>
				<category><![CDATA[Hyper-V]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Tools and Utilities]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/</guid>
		<description><![CDATA[I am always looking for tools to allow me to do more by doing less. Administering Hyper-V with PowerShell can be tedious. James O’Neill’s PowerShell Management Library for Hyper-V is a great tool to improve automation of Hyper-V management using PowerShell. As a tester, I am constantly creating new environments, installing our product, taking snapshots, [...]]]></description>
			<content:encoded><![CDATA[<p>I am always looking for tools to allow me to do more by doing less. Administering Hyper-V with PowerShell can be tedious. James O’Neill’s <a href="http://pshyperv.codeplex.com/" target="_blank">PowerShell Management Library for Hyper-V</a> is a great tool to improve automation of Hyper-V management using PowerShell.</p>  <p>As a tester, I am constantly creating new environments, installing our product, taking snapshots, ect. Doing this by hand is a waste of time in my opinion. Doing this with a script makes life easier and frees up my time. </p>  <p>Typically, I prefer to create is to create one VM and to have other VMs inherit from that base image. My second VM (the first child to inherit from the base), I will install daily builds of our product. I will then create a third child, which I use a sandbox. I can easily delete it and recreate as needed without having to install our product over again. I have not consistently found success with using snapshots, so I prefer to use differencing disks. The examples below use differencing disks. </p>  <p>This first code block shows how I am using the PowerShell management library to simply the creation of a base VM. There is nothing magic about it. It’s pretty strait-forward. I create a VM, give it a name, set the CPU count, memory size, network adapters, hard drive, and DVD drive.</p>  <pre class="code"><span style="color: purple">$server </span><span style="color: red">= </span><span style="color: maroon">&quot;my-dev-server&quot;
</span><span style="color: purple">$vmName </span><span style="color: red">= </span><span style="color: maroon">&quot;TestParentVM&quot;
</span><span style="color: purple">$vmVirtualSwitch </span><span style="color: red">= </span><span style="color: maroon">&quot;My Virtual Network&quot;

</span><span style="color: green"># create a new virtual machine
</span><span style="color: purple">$vm </span><span style="color: red">= </span><span style="color: black">New-VM </span><span style="color: purple">$vmName </span><span style="color: black">-server </span><span style="color: purple">$server

</span><span style="color: green"># set cpu count
</span><span style="color: black">Set-VMCPUCount </span><span style="color: purple">$vm </span><span style="color: black">2 -server </span><span style="color: purple">$server

</span><span style="color: green"># set memory size
</span><span style="color: black">Set-VMMemory </span><span style="color: purple">$vm </span><span style="color: black">2 -memory 4GB -server </span><span style="color: purple">$server

</span><span style="color: green"># add a legacy network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch </span><span style="color: black">-legacy

</span><span style="color: green"># add a default VMBus (non-legacy) network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch

</span><span style="color: green"># add the hard drive to the VM
</span><span style="color: black">Add-VMNewHardDisk –vm </span><span style="color: purple">$vm </span><span style="color: black">-controllerID 0 -lun 0 -vhdpath </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmName.vhd&quot; </span><span style="color: black">-size 20GB

</span><span style="color: green"># add the DVD with bootup ISO
</span><span style="color: black">Add-VMDRIVE –vm </span><span style="color: purple">$vm </span><span style="color: black">1 1 -server </span><span style="color: purple">$server </span><span style="color: black">-DVD 

</span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;Operation complete.&quot;</span></pre>
<a href="http://11011.net/software/vspaste"></a>

<p>The next code block will create a differencing disk pointing to the parent created in the previous example. I create the usual, VM, CPU count, ect. What makes this a differencing disk is how the VHD is created by specifying the parent. I do some cleanup in this routine by deleting any previously created VMs or VHDs, and I loop through the creation a failure preventative. </p>

<pre class="code"><span style="color: purple">$server </span><span style="color: red">= </span><span style="color: maroon">&quot;my-dev-server&quot;
</span><span style="color: purple">$vmName </span><span style="color: red">= </span><span style="color: maroon">&quot;TestChildVM&quot;
</span><span style="color: purple">$vmParent </span><span style="color: red">= </span><span style="color: maroon">&quot;TestParentVM&quot;
</span><span style="color: purple">$vmVirtualSwitch </span><span style="color: red">= </span><span style="color: maroon">&quot;My Virtual Network&quot;

</span><span style="color: blue">#region </span><span style="color: black">functions - feel free to move to a separate file

</span><span style="color: blue">Function </span><span style="color: #5f9ea0">DeleteVhd
</span><span style="color: black">{
    </span><span style="color: blue">Param </span><span style="color: black">(</span><span style="color: purple">$pathToVhd</span><span style="color: black">)
    </span><span style="color: green"># delete the disk that was added if it exists
    </span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: #5f9ea0">test-path -path </span><span style="color: purple">$pathToVhd</span><span style="color: black">)
    {
        </span><span style="color: #5f9ea0">Remove-Item -Path </span><span style="color: purple">$pathToVhd </span><span style="color: #5f9ea0">-Force
    </span><span style="color: black">}
}

</span><span style="color: blue">#endregion

</span><span style="color: green"># delete the VHD if it already exists
</span><span style="color: #5f9ea0">DeleteVhd </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmName.vhd&quot;

</span><span style="color: green"># delete the VM if it already exists
</span><span style="color: black">Remove-VM -vm </span><span style="color: purple">$vmName </span><span style="color: black">-server </span><span style="color: purple">$server

</span><span style="color: green"># create a new virtual machine
</span><span style="color: purple">$vm </span><span style="color: red">= </span><span style="color: black">New-VM </span><span style="color: purple">$vmName </span><span style="color: black">-server </span><span style="color: purple">$server

</span><span style="color: green"># get the vm
</span><span style="color: purple">$vm </span><span style="color: red">= </span><span style="color: black">Get-VM </span><span style="color: purple">$vmName

</span><span style="color: green"># set cpu count
</span><span style="color: black">Set-VMCPUCount </span><span style="color: purple">$vm </span><span style="color: black">2 -server </span><span style="color: purple">$server

</span><span style="color: green"># set memory size
</span><span style="color: black">Set-VMMemory </span><span style="color: purple">$vm </span><span style="color: black">2 -memory 4GB -server </span><span style="color: purple">$server

</span><span style="color: green"># get VM Nics available
</span><span style="color: purple">$vmNics </span><span style="color: red">= </span><span style="color: black">Get-VMNic -server </span><span style="color: purple">$server </span><span style="color: black">-vmbus -legacy
</span><span style="color: purple">$vmNicSwitchList </span><span style="color: red">= </span><span style="color: #5f9ea0">New-Object </span><span style="color: maroon">System.Collections.ArrayList

</span><span style="color: green"># get VM Nic Switch available for each VM Nic and add it to our list
</span><span style="color: blue">foreach </span><span style="color: black">(</span><span style="color: purple">$vmNic </span><span style="color: blue">in </span><span style="color: purple">$vmNics</span><span style="color: black">)
{
    </span><span style="color: purple">$vmSwitchElementName </span><span style="color: red">= </span><span style="color: black">(Get-VMNicSwitch </span><span style="color: purple">$vmNic</span><span style="color: black">).ElementName
    </span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">.Contains(</span><span style="color: purple">$vmSwitchElementName</span><span style="color: black">) </span><span style="color: red">-ne </span><span style="color: blue">$true</span><span style="color: black">)
    {
        </span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">.Add(</span><span style="color: purple">$vmSwitchElementName</span><span style="color: black">)
    }
}

</span><span style="color: green"># Use the first available VM Nic Switch - this assumes 
# I do not create more than on per each environment.
</span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">.Count </span><span style="color: red">-gt </span><span style="color: black">0)
{
    </span><span style="color: purple">$vmVirtualSwitch </span><span style="color: red">= </span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">[0]
}

</span><span style="color: green"># add a legacy network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch </span><span style="color: black">-legacy

</span><span style="color: green"># add a default VMBus (non-legacy) network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch

</span><span style="color: green"># add the hard drive to the VM
</span><span style="color: purple">$parent </span><span style="color: red">= </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmParent.vhd&quot;
</span><span style="color: purple">$vhdPath </span><span style="color: red">= </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmName.vhd&quot;
</span><span style="color: black">Add-VMNewHardDisk –vm </span><span style="color: purple">$vm </span><span style="color: black">-controllerID 0 -lun 0 -vhdpath </span><span style="color: purple">$vhdPath </span><span style="color: black">-parent </span><span style="color: purple">$parent

</span><span style="color: green"># get the VM to see if a disk is attached to it, if it is not, then it failed
</span><span style="color: purple">$disks </span><span style="color: red">= </span><span style="color: black">Get-VMDisk -vm </span><span style="color: purple">$vm
$count </span><span style="color: red">= </span><span style="color: black">1

</span><span style="color: green"># if the disk was not successfully added, try and add it again
</span><span style="color: blue">while </span><span style="color: black">(</span><span style="color: purple">$disks </span><span style="color: red">-eq </span><span style="color: purple">$null </span><span style="color: red">-and </span><span style="color: purple">$count </span><span style="color: red">-le </span><span style="color: black">5)
{
    </span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;RETRY $count - The disk was not properly added. Attempting to retry.&quot;
    
    </span><span style="color: green"># delete the disk that was added
    </span><span style="color: #5f9ea0">DeleteVhd </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmName.vhd&quot;
    
    </span><span style="color: black">Add-VMNewHardDisk –vm </span><span style="color: purple">$vm </span><span style="color: black">-controllerID 0 -lun 0 -vhdpath </span><span style="color: purple">$vhdPath </span><span style="color: black">-parent </span><span style="color: purple">$parent
    
    $disks </span><span style="color: red">= </span><span style="color: black">Get-VMDisk -vm </span><span style="color: purple">$vm
    $count</span><span style="color: red">++
</span><span style="color: black">}

</span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: purple">$disks </span><span style="color: red">-eq </span><span style="color: purple">$null</span><span style="color: black">)
{
    </span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;Operation failed to create this virtual machine. Contact an admin.&quot;
</span><span style="color: black">}
</span><span style="color: blue">else
</span><span style="color: black">{
    </span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;Operation completed successfully. Attempting to start the VM.&quot;
    </span><span style="color: black">Start-VM -vm </span><span style="color: purple">$vm </span><span style="color: black">-wait
}</span></pre>
<a href="http://11011.net/software/vspaste"></a>

<p>I have found that the VM creation is not consistently successful on the first pass, so I have added the while loop. Since adding that, I have not had any issues.</p>

<p>I hope these help. They should be easy to change if you prefer snapshots versus differencing disks. Thanks to James O’Neill for creating this library. It makes administering Hyper-V much easier. It is available via <a title="CodePlex" href="http://www.codeplex.com/" target="_blank">CodePlex</a>, where the latest release, updates, and forum support can be found. </p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Installing Windows 7</title>
		<link>http://elegantcode.com/2009/02/09/installing-windows-7/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=installing-windows-7</link>
		<comments>http://elegantcode.com/2009/02/09/installing-windows-7/#comments</comments>
		<pubDate>Mon, 09 Feb 2009 21:14:36 +0000</pubDate>
		<dc:creator>Alex Mueller</dc:creator>
				<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Operating Systems]]></category>
		<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/02/09/installing-windows-7/</guid>
		<description><![CDATA[The short story is this. If you are accessing Windows 7 from your MSDN subscriptions, save yourself time and frustration by installing the Windows 7 Beta, not the Windows 7 Beta Checked Build. See available downloads here. This past weekend, I decided to upgrade my work laptop from Vista Enterprise to Windows 7 Ultimate Beta. [...]]]></description>
			<content:encoded><![CDATA[<p>The short story is this. If you are accessing Windows 7 from your MSDN subscriptions, save yourself time and frustration by installing the Windows 7 Beta, not the Windows 7 Beta Checked Build. <a href="http://msdn.microsoft.com/en-us/subscriptions/cc137115.aspx" target="_blank">See available downloads here</a>.</p>  <p>This past weekend, I decided to upgrade my work laptop from Vista Enterprise to Windows 7 Ultimate Beta. I was unable to upgrade from Vista Enterprise to 7 Ultimate because that action is not supported. I then tried to upgrade from Enterprise to 7 Enterprise, but I was unable to upgrade from a staged build to a non-staged build. I decided to repave entirely, choosing Windows 7 Ultimate Beta, and I tried to do all of this on a Friday afternoon, two hours before leaving.</p>  <p>I installed Windows 7 Beta Checked Build (x86) - DVD (English), last updated on January 14, 2009,&#160; from my MSDN subscription. I did not install an internal build. Instead, I decided to go with what is publicly available via MSDN. </p>  <p>Why did I go with a <a href="http://msdn.microsoft.com/en-us/library/ms792442.aspx" target="_blank">Checked Build</a>? Because I failed to read the details describing it. What it cost me in time and frustration, I gain in valuable learning experiences. So it was not a total loss. I received a number of buggy issues with the checked build, mainly the inability for Windows Update to properly download all of my necessary updates, including my video drivers and smart card reader, where the latter enables me to remotely access my work domain. </p>  <p>I gave up and decided to download and install the Windows 7 Beta – DVD (English). Everything works great. I was able to get online, download all of my updates, and connect to my work domain. No issues found so far, and no annoying assertion error popups. </p>  <p>My favorite Windows 7 feature so far (non-UI related) is that PowerShell 2.0 is installed by default. PowerShell 2.0 provides more functionality for remoting, among other enhancements.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/02/09/installing-windows-7/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>PowerShell Documentation</title>
		<link>http://elegantcode.com/2008/12/17/powershell-documentation/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-documentation</link>
		<comments>http://elegantcode.com/2008/12/17/powershell-documentation/#comments</comments>
		<pubDate>Wed, 17 Dec 2008 20:36:54 +0000</pubDate>
		<dc:creator>Alex Mueller</dc:creator>
				<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/12/17/powershell-documentation/</guid>
		<description><![CDATA[PowerShell documentation, you are too honest. Get-Help Remove-Item -Full As I was retrieving information on "Remove-Item," this is what I came across. There is more detail beyond what I am showing, but pay attention to what is bolded. NAME&#160;&#160;&#160; Remove-Item SYNOPSIS&#160;&#160;&#160; Deletes the specified items. SYNTAX&#160;&#160;&#160; Remove-Item [-path] &#60;string[]&#62; [-recurse] [-force] [-include &#60;string[]&#62;] [-&#160;&#160;&#160; exclude [...]]]></description>
			<content:encoded><![CDATA[<p>PowerShell documentation, you are too honest. </p> <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:F2210F5F-69EB-4d4c-AFF7-B8A050E9CC72:2ed0ad7a-f3da-498d-a817-1bb0c8b8f8c3" class="wlWriterSmartContent"><pre  style="width:100%;;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #000000;">Get</span><span style="color: #000000;">-</span><span style="color: #000000;">Help Remove</span><span style="color: #000000;">-</span><span style="color: #000000;">Item </span><span style="color: #000000;">-</span><span style="color: #000000;">Full</span></div></pre></div>
<p>As I was retrieving information on "Remove-Item," this is what I came across. There is more detail beyond what I am showing, but pay attention to what is <strong>bolded</strong>. </p>
<blockquote>
<p>NAME<br>&nbsp;&nbsp;&nbsp; Remove-Item 
<p>SYNOPSIS<br>&nbsp;&nbsp;&nbsp; Deletes the specified items. 
<p>SYNTAX<br>&nbsp;&nbsp;&nbsp; Remove-Item [-path] &lt;string[]&gt; [-recurse] [-force] [-include &lt;string[]&gt;] [-<br>&nbsp;&nbsp;&nbsp; exclude &lt;string[]&gt;] [-filter &lt;string&gt;] [-credential &lt;PSCredential&gt;] [-whatI<br>&nbsp;&nbsp;&nbsp; f] [-confirm] [&lt;CommonParameters&gt;] 
<p>&nbsp;&nbsp;&nbsp; Remove-Item [-literalPath] &lt;string[]&gt; [-recurse] [-force] [-include &lt;string<br>&nbsp;&nbsp;&nbsp; []&gt;] [-exclude &lt;string[]&gt;] [-filter &lt;string&gt;] [-credential &lt;PSCredential&gt;]<br>&nbsp;&nbsp;&nbsp; [-whatIf] [-confirm] [&lt;CommonParameters&gt;] 
<p>DETAILED DESCRIPTION<br>&nbsp;&nbsp;&nbsp; The Remove-Item cmdlet deletes one or more items. Because it is supported b<br>&nbsp;&nbsp;&nbsp; y many providers, it can delete many different types of items, including fi<br>&nbsp;&nbsp;&nbsp; les, directories, registry keys, variables, aliases, certificates, and func<br>&nbsp;&nbsp;&nbsp; tions. 
<p>PARAMETERS<br>&nbsp;&nbsp;&nbsp; -path &lt;string[]&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Specifies a path to the items being removed. Wildcards are permitted. T<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; he parameter name ("-Path") is optional. 
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Required?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; true<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Position?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 1<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Default value&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; N/A - The path must be specified<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept pipeline input?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; true (ByValue, ByPropertyName)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept wildcard characters?&nbsp; true 
<p>&nbsp;&nbsp;&nbsp; -recurse &lt;SwitchParameter&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Deletes the items in the specified locations and in all child items of<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; the locations. 
<p><strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; The Recurse parameter in this cmdlet does not work properly. </strong>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Required?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; false<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Position?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; named<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Default value&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; False<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept pipeline input?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; false<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept wildcard characters?&nbsp; false 
<p><strong></strong>&nbsp;</p></blockquote>
<p>"Hmmm... Am I feeling lucky? Ahhh, what the hell, let's do it."</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:F2210F5F-69EB-4d4c-AFF7-B8A050E9CC72:a3ee0edf-63f8-43fc-a4fb-22c6277656f8" class="wlWriterSmartContent"><pre  style="width:100%;;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #000000;">Remove</span><span style="color: #000000;">-</span><span style="color: #000000;">Item </span><span style="color: #800000;">&quot;</span><span style="color: #800000;">C:\</span><span style="color: #800000;">&quot;</span><span style="color: #000000;"> </span><span style="color: #000000;">-</span><span style="color: #000000;">Recurse</span></div></pre></div>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/12/17/powershell-documentation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Automate Daily Tasks with PowerShell</title>
		<link>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring</link>
		<comments>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/#comments</comments>
		<pubDate>Mon, 26 Oct 2009 05:00:40 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/</guid>
		<description><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about Fluent Specification Extensions in a past blog. Recently I wanted to execute a PowerShell script [...]]]></description>
			<content:encoded><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about <a href="http://staxmanade.blogspot.com/2009/02/fluent-specification-extensions.html">Fluent Specification Extensions</a> in a past blog.

Recently I wanted to execute a PowerShell script to do some automated <a href="http://en.wikipedia.org/wiki/Functional_testing">functional testing</a>. I wanted to execute an application and apply some assertions on the output of the software(basically running a console app, parse the xml output and assert on values in the output).
<blockquote>FYI: I’m very new to PowerShell, so any suggestions on how I implemented the below are welcome…</blockquote>
I’ve seen a couple examples of writing test assertions in PowerShell out there. One example is <a href="http://www.psunit.org/">PSUnit</a>; however, this seemed a little heavy for my needs and not quite the syntactic sugar I was looking for.

Besides the syntax flavor I was desiring, another thing I wanted to do was leverage the power of NUnit.Framework’s assertion capabilities. I like the error messages generated when strings and other objects fail the assertion.
<h5>Examples of end result ShouldLookLike()…</h5>
$true.ShouldBeTrue()
$false.ShouldBeFalse()
"a".ShouldEqual("a")
"a".ShouldNotEqual("b")
<h5><strong>Step 1</strong>: Figure out how to write a C# style <a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx">extension method</a> in PowerShell.</h5>
<blockquote>I found a great blog post describing how to extend any PowerShell object to add extension methods.

<a href="http://bartdesmet.net/blogs/bart/archive/2007/09/06/extension-methods-in-windows-powershell.aspx">Extension Methods in Windows PowerShell</a></blockquote>
In short, to extend types in PowerShell leveraging the <a href="http://msdn.microsoft.com/en-us/library/ms714419(VS.85).aspx">Extended Type System</a>, you need to define them in an xml file and import the method definitions into the PowerShell runtime instance.

Below is PowerShell XML definition for my NUnit Specification Extensions.
<pre class="brush: xml;">&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;Types&gt;
    &lt;Type&gt;
        &lt;Name&gt;System.Object&lt;/Name&gt;
        &lt;Members&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeFalse&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsFalse($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeTrue&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsTrue($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldNotEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreNotEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
        &lt;/Members&gt;
    &lt;/Type&gt;
&lt;/Types&gt;</pre>
<h4></h4>
Take the above XML and save it to a file…
<blockquote>NOTE: the file HAS to be saved with the extension <strong>.ps1xml</strong>

Ex: NunitSpecificationPowerShellExtensions<strong>.ps1xml</strong></blockquote>
<h4></h4>
<h5>Step 2: Load the extended type definition into the PowerShell runtime.</h5>
Once you’ve saved the XML extended types to a file, you need to load it into the PowerShell runtime by executing the command below.
<blockquote>
Update-TypeData -PrependPath NunitSpecificationPowerShellExtensions.ps1xml</blockquote>
Before executing the above statement…Let’s quickly look at a System.String’s members and properties – just to show you what the extension methods look like when applied inside of the runtime.<a href="http://elegantcode.com/wp-content/uploads/2009/10/image3.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb2.png" border="0" alt="image" width="586" height="479" /></a>

After executing the Update-TypeData command you’ll notice there are a number of “ScriptMethod” MemberTypes added to the object.

<a href="http://elegantcode.com/wp-content/uploads/2009/10/image4.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb3.png" border="0" alt="image" width="600" height="580" /></a>

Now if you try to execute one of those newly added extension methods, you may get the following error…

PS C:\&gt; $testVar.<strong>ShouldEqual</strong>("hello world")

Exception calling "ShouldEqual" with "1" argument(s): "<strong>Unable to find type [NUnit.Framework.Assert]: make sure that the

assembly containing this type is loaded.</strong>"

At line:1 char:21

+ $testVar.ShouldEqual &lt;&lt;&lt;&lt; ("hello world")

+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

+ FullyQualifiedErrorId : ScriptMethodRuntimeException

This is because we need to load the NUnit.Framework assembly into the runtime before we can leverage the extension methods.
<blockquote>[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null</blockquote>
Now that the extension methods have been defined and loaded into the runtime, NUnit.Framework is loaded, we can now use the methods on any object that inherits from System.Object (which, as far as I know, is everything in PowerShell).

And now, everything you need in one script (if you have the xml extended type file saved somewhere…)
<pre>#
# Update-TypeData -prependPath C:\Code\NunitSpecificationPowerShellExtensions.ps1xml
#

[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null

$true.ShouldBeTrue()

$false.ShouldBeFalse()

"a".ShouldEqual("a")

"a".ShouldNotEqual("b")</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Elegant Code &#187; PowerShell</title>
	<atom:link href="http://elegantcode.com/category/microsoft/powershell/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Silverlight Profiling PowerShell helper.</title>
		<link>http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=silverlight-profiling-powershell-helper</link>
		<comments>http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/#comments</comments>
		<pubDate>Sat, 15 May 2010 16:47:22 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/</guid>
		<description><![CDATA[I was playing around with some Silverlight profiling the other night to see if I could find any obvious issues with my open source project StatLight and wound up writing a little script in PowerShell I hoped someone might find helpful. But I didn’t know you could profile a Silverlight app. I didn’t until I [...]]]></description>
			<content:encoded><![CDATA[<p>I was playing around with some Silverlight profiling the other night to see if I could find any obvious issues with my open source project <a href="http://statlight.net" target="_blank">StatLight</a> and wound up writing a little script in PowerShell I hoped someone might find helpful.</p>  <h4>But I didn’t know you could profile a Silverlight app.</h4>  <p>I didn’t until I started doing some digging online. Now, the Silverlight profiling story (at least from what I’ve seen/tried) is not near the easy of say <a href="http://www.red-gate.com/products/ants_performance_profiler/index.htm">Redgate ANTS Performance Profiler</a>. However, it’s do-able. (And with this helper script – hopefully a little simpler?)</p>  <h4>How can I profile a Silverlight Application?</h4>  <p>I would recommend you read the following blog, which explains one way of doing it very well.</p>  <p><a title="http://blogs.msdn.com/profiler/archive/2010/04/26/vs2010-silverlight-4-profiling.aspx" href="http://blogs.msdn.com/profiler/archive/2010/04/26/vs2010-silverlight-4-profiling.aspx">http://blogs.msdn.com/profiler/archive/2010/04/26/vs2010-silverlight-4-profiling.aspx</a></p>  <h4>So… what’s this script for?</h4>  <p>If you read the blog above, or have done this before, then you probably noticed that there was quite a series of commands you had to execute before you could wind up with a performance report. </p>  <p>I threw together a quick little PowerShell script in an attempt to automate smooth out the process.</p>  <h4>Hot do I use it?</h4>  <ol>   <li>Download the script &amp; save it somewhere. <a href="http://github.com/staxmanade/Scripts/blob/master/SilverlightProfiler.ps1"><strong>http://github.com/staxmanade/Scripts/blob/master/SilverlightProfiler.ps1</strong></a> </li>    <li>Open the PowerShell console. cd to the directory your xap/assemblies are stored.      <br />(EX: {myProject}\Bin\Debug\ ) </li>    <li>Execute:      <br />{pathToScript}\SilverlightProfiler.ps1 -urlPath &quot;{myProject}\Bin\Debug\TestPage.html&quot; </li>    <li>When your done profiling press enter to signal that your done.      <p></p> Once complete, it will print the location your profiling report was saved. You can then open it with Visual Studio.</li> </ol>  <h5>Couple of disclaimers.</h5>  <ul>   <li>Some paths are hard-coded to my x86 machine. </li>    <li>I had troubles running the built in visual studio .bat files (from powershell) that are supposed to set the environment variables. So I extracted out what vars I could find to make it work. </li>    <li>I’m not a profiling expert – just hacked this together to get it to work for me.</li> </ul>  <p>I hope this is useful, and if you know of a better way, I’m always interested in hearing your feedback.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Powershell: Load assembly without locking file.</title>
		<link>http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-load-assembly-without-locking-file</link>
		<comments>http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/#comments</comments>
		<pubDate>Wed, 23 Dec 2009 05:40:23 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/</guid>
		<description><![CDATA[I have a set of PowerShell build scripts and ran into a case where I needed to load an assembly (to get the assembly’s version) and still (at a later time) work with the assembly file on disk. A typical way to load an assembly within PowerShell is to use the Assembly.LoadFrom(filePath) # Powershell [System.Reflection.Assembly]::LoadFrom($assemblyPath) [...]]]></description>
			<content:encoded><![CDATA[<p>I have a set of PowerShell build scripts and ran into a case where I needed to load an assembly (to get the assembly’s version) and still (at a later time) work with the assembly file on disk.</p>  <p>A typical way to load an assembly within PowerShell is to use the Assembly.LoadFrom(filePath)</p>  <blockquote>   <p># Powershell</p>    <p>[System.Reflection.Assembly]::LoadFrom($assemblyPath)</p> </blockquote>  <p><a href="http://elegantcode.com/wp-content/uploads/2009/12/image9.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://elegantcode.com/wp-content/uploads/2009/12/image_thumb9.png" width="690" height="391" /></a> </p>  <p>Except the problem with this (in my case) was it would <strong>lock the file for the lifespan of the PowerShell console instance</strong>. I didn’t want to have to close and re-open the PowerShell console every time I need to run a build so there had to be a work-around for this.</p>  <p>After searching the web for a solution, I couldn’t find anything that was “easy” and worth the effort to get it to work.</p>  <blockquote>   <p>EX: One solution was to create a new AppDomain, do the necessary work and the close the AppDomain which would release the lock on the file.</p>    <p>I’ve never done this myself, and even thought there is example code out there to get this accomplished, it just seemed over the top for what I was trying to do, and back to my previous criteria it wasn’t “worth the effort to get it to work”</p> </blockquote>  <p>Then I remembered in a previous life I used an overload that took an array of bytes to load the an assembly.</p>  <blockquote>   <p>[System.Reflection.Assembly]::Load($assemblyBytes)</p> </blockquote>  <p>After spiking it in PowerShell with the below test. I was quite happy with the solution, so I thought I’d throw it out there.</p>  <p>Just stream the assembly from disk into a byte array manually, and call assembly load from there.</p>  <p>Here’s my test case which shows that the file is not locked after it was loaded into the PowerShell runtime</p>  <pre>$file = &quot;.\Moq.dll&quot;
$tempFileName = &quot;.\Moq-Renamed.dll&quot;

$fileStream = ([System.IO.FileInfo] (Get-Item $file)).OpenRead();
$assemblyBytes = new-object byte[] $fileStream.Length
$fileStream.Read($assemblyBytes, 0, $fileStream.Length);
$fileStream.Close();

$assemblyLoaded = [System.Reflection.Assembly]::Load($assemblyBytes);

# notice that we can move the file on disk after 
# it's loaded into the powershell runtime
Move-Item $file $tempFileName
Move-Item $tempFileName $file 

# and display the assembly information to show we still have it in memory
echo $assemblyLoaded</pre>

<p>After that test passed, and the main reason I wanted to do this, I wrote the “get-assembly-version” PowerShell function.</p>

<pre><strike>function get-assembly-version() {
    param([string] $file)
    
    # load the assembly bytes quickly - as to not lock the file for too long
    $fileStream = ([System.IO.FileInfo] (Get-Item $file)).OpenRead()
    $assemblyBytes = new-object byte[] $fileStream.Length
    $fileStream.Read($assemblyBytes, 0, $fileStream.Length) | Out-Null #out null this because this function should only return the version &amp; this call was outputting some garbage number
    $fileStream.Close()
    
    # return the version of the assembly
    [System.Reflection.Assembly]::Load($assemblyBytes).GetName().Version;
}

$version = get-assembly-version(&quot;.\Moq.dll&quot;)

echo &quot;Loaded v$($version.Major).$($version.Minor).$($version.Build).$($version.Revision) version of $file&quot;</strike></pre>
Hope this helps someone out there! 

<p></p>

<p>&#160;</p>

<p><strong>UPDATE:</strong></p>

<p><a href="http://achuebrigens.wordpress.com">Martin</a> commented below on a much better solution to the assembly version info problem. Amazing how complicated we can make things if we don’t know the path.</p>

<pre>
function get-assembly-version() {
    param([string] $file)
    
    $version = [System.Reflection.AssemblyName]::GetAssemblyName($file).Version;
    
    #format the version and output it...
    $version
}</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Integration Test Brought to you by Powershell &amp; NUnit &#8211; with a Little Specification Syntax for Flavoring</title>
		<link>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring</link>
		<comments>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/#comments</comments>
		<pubDate>Mon, 26 Oct 2009 05:00:40 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/</guid>
		<description><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about Fluent Specification Extensions in a past blog. Recently I wanted to execute a PowerShell script [...]]]></description>
			<content:encoded><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about <a href="http://staxmanade.blogspot.com/2009/02/fluent-specification-extensions.html">Fluent Specification Extensions</a> in a past blog.

Recently I wanted to execute a PowerShell script to do some automated <a href="http://en.wikipedia.org/wiki/Functional_testing">functional testing</a>. I wanted to execute an application and apply some assertions on the output of the software(basically running a console app, parse the xml output and assert on values in the output).
<blockquote>FYI: I’m very new to PowerShell, so any suggestions on how I implemented the below are welcome…</blockquote>
I’ve seen a couple examples of writing test assertions in PowerShell out there. One example is <a href="http://www.psunit.org/">PSUnit</a>; however, this seemed a little heavy for my needs and not quite the syntactic sugar I was looking for.

Besides the syntax flavor I was desiring, another thing I wanted to do was leverage the power of NUnit.Framework’s assertion capabilities. I like the error messages generated when strings and other objects fail the assertion.
<h5>Examples of end result ShouldLookLike()…</h5>
$true.ShouldBeTrue()
$false.ShouldBeFalse()
"a".ShouldEqual("a")
"a".ShouldNotEqual("b")
<h5><strong>Step 1</strong>: Figure out how to write a C# style <a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx">extension method</a> in PowerShell.</h5>
<blockquote>I found a great blog post describing how to extend any PowerShell object to add extension methods.

<a href="http://bartdesmet.net/blogs/bart/archive/2007/09/06/extension-methods-in-windows-powershell.aspx">Extension Methods in Windows PowerShell</a></blockquote>
In short, to extend types in PowerShell leveraging the <a href="http://msdn.microsoft.com/en-us/library/ms714419(VS.85).aspx">Extended Type System</a>, you need to define them in an xml file and import the method definitions into the PowerShell runtime instance.

Below is PowerShell XML definition for my NUnit Specification Extensions.
<pre class="brush: xml;">&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;Types&gt;
    &lt;Type&gt;
        &lt;Name&gt;System.Object&lt;/Name&gt;
        &lt;Members&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeFalse&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsFalse($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeTrue&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsTrue($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldNotEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreNotEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
        &lt;/Members&gt;
    &lt;/Type&gt;
&lt;/Types&gt;</pre>
<h4></h4>
Take the above XML and save it to a file…
<blockquote>NOTE: the file HAS to be saved with the extension <strong>.ps1xml</strong>

Ex: NunitSpecificationPowerShellExtensions<strong>.ps1xml</strong></blockquote>
<h4></h4>
<h5>Step 2: Load the extended type definition into the PowerShell runtime.</h5>
Once you’ve saved the XML extended types to a file, you need to load it into the PowerShell runtime by executing the command below.
<blockquote>
Update-TypeData -PrependPath NunitSpecificationPowerShellExtensions.ps1xml</blockquote>
Before executing the above statement…Let’s quickly look at a System.String’s members and properties – just to show you what the extension methods look like when applied inside of the runtime.<a href="http://elegantcode.com/wp-content/uploads/2009/10/image3.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb2.png" border="0" alt="image" width="586" height="479" /></a>

After executing the Update-TypeData command you’ll notice there are a number of “ScriptMethod” MemberTypes added to the object.

<a href="http://elegantcode.com/wp-content/uploads/2009/10/image4.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb3.png" border="0" alt="image" width="600" height="580" /></a>

Now if you try to execute one of those newly added extension methods, you may get the following error…

PS C:\&gt; $testVar.<strong>ShouldEqual</strong>("hello world")

Exception calling "ShouldEqual" with "1" argument(s): "<strong>Unable to find type [NUnit.Framework.Assert]: make sure that the

assembly containing this type is loaded.</strong>"

At line:1 char:21

+ $testVar.ShouldEqual &lt;&lt;&lt;&lt; ("hello world")

+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

+ FullyQualifiedErrorId : ScriptMethodRuntimeException

This is because we need to load the NUnit.Framework assembly into the runtime before we can leverage the extension methods.
<blockquote>[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null</blockquote>
Now that the extension methods have been defined and loaded into the runtime, NUnit.Framework is loaded, we can now use the methods on any object that inherits from System.Object (which, as far as I know, is everything in PowerShell).

And now, everything you need in one script (if you have the xml extended type file saved somewhere…)
<pre>#
# Update-TypeData -prependPath C:\Code\NunitSpecificationPowerShellExtensions.ps1xml
#

[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null

$true.ShouldBeTrue()

$false.ShouldBeFalse()

"a".ShouldEqual("a")

"a".ShouldNotEqual("b")</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>PowerShell Management Library for Hyper-V</title>
		<link>http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-management-library-for-hyper-v</link>
		<comments>http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/#comments</comments>
		<pubDate>Wed, 25 Mar 2009 21:46:16 +0000</pubDate>
		<dc:creator>Alex Mueller</dc:creator>
				<category><![CDATA[Hyper-V]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Tools and Utilities]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/</guid>
		<description><![CDATA[I am always looking for tools to allow me to do more by doing less. Administering Hyper-V with PowerShell can be tedious. James O’Neill’s PowerShell Management Library for Hyper-V is a great tool to improve automation of Hyper-V management using PowerShell. As a tester, I am constantly creating new environments, installing our product, taking snapshots, [...]]]></description>
			<content:encoded><![CDATA[<p>I am always looking for tools to allow me to do more by doing less. Administering Hyper-V with PowerShell can be tedious. James O’Neill’s <a href="http://pshyperv.codeplex.com/" target="_blank">PowerShell Management Library for Hyper-V</a> is a great tool to improve automation of Hyper-V management using PowerShell.</p>  <p>As a tester, I am constantly creating new environments, installing our product, taking snapshots, ect. Doing this by hand is a waste of time in my opinion. Doing this with a script makes life easier and frees up my time. </p>  <p>Typically, I prefer to create is to create one VM and to have other VMs inherit from that base image. My second VM (the first child to inherit from the base), I will install daily builds of our product. I will then create a third child, which I use a sandbox. I can easily delete it and recreate as needed without having to install our product over again. I have not consistently found success with using snapshots, so I prefer to use differencing disks. The examples below use differencing disks. </p>  <p>This first code block shows how I am using the PowerShell management library to simply the creation of a base VM. There is nothing magic about it. It’s pretty strait-forward. I create a VM, give it a name, set the CPU count, memory size, network adapters, hard drive, and DVD drive.</p>  <pre class="code"><span style="color: purple">$server </span><span style="color: red">= </span><span style="color: maroon">&quot;my-dev-server&quot;
</span><span style="color: purple">$vmName </span><span style="color: red">= </span><span style="color: maroon">&quot;TestParentVM&quot;
</span><span style="color: purple">$vmVirtualSwitch </span><span style="color: red">= </span><span style="color: maroon">&quot;My Virtual Network&quot;

</span><span style="color: green"># create a new virtual machine
</span><span style="color: purple">$vm </span><span style="color: red">= </span><span style="color: black">New-VM </span><span style="color: purple">$vmName </span><span style="color: black">-server </span><span style="color: purple">$server

</span><span style="color: green"># set cpu count
</span><span style="color: black">Set-VMCPUCount </span><span style="color: purple">$vm </span><span style="color: black">2 -server </span><span style="color: purple">$server

</span><span style="color: green"># set memory size
</span><span style="color: black">Set-VMMemory </span><span style="color: purple">$vm </span><span style="color: black">2 -memory 4GB -server </span><span style="color: purple">$server

</span><span style="color: green"># add a legacy network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch </span><span style="color: black">-legacy

</span><span style="color: green"># add a default VMBus (non-legacy) network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch

</span><span style="color: green"># add the hard drive to the VM
</span><span style="color: black">Add-VMNewHardDisk –vm </span><span style="color: purple">$vm </span><span style="color: black">-controllerID 0 -lun 0 -vhdpath </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmName.vhd&quot; </span><span style="color: black">-size 20GB

</span><span style="color: green"># add the DVD with bootup ISO
</span><span style="color: black">Add-VMDRIVE –vm </span><span style="color: purple">$vm </span><span style="color: black">1 1 -server </span><span style="color: purple">$server </span><span style="color: black">-DVD 

</span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;Operation complete.&quot;</span></pre>
<a href="http://11011.net/software/vspaste"></a>

<p>The next code block will create a differencing disk pointing to the parent created in the previous example. I create the usual, VM, CPU count, ect. What makes this a differencing disk is how the VHD is created by specifying the parent. I do some cleanup in this routine by deleting any previously created VMs or VHDs, and I loop through the creation a failure preventative. </p>

<pre class="code"><span style="color: purple">$server </span><span style="color: red">= </span><span style="color: maroon">&quot;my-dev-server&quot;
</span><span style="color: purple">$vmName </span><span style="color: red">= </span><span style="color: maroon">&quot;TestChildVM&quot;
</span><span style="color: purple">$vmParent </span><span style="color: red">= </span><span style="color: maroon">&quot;TestParentVM&quot;
</span><span style="color: purple">$vmVirtualSwitch </span><span style="color: red">= </span><span style="color: maroon">&quot;My Virtual Network&quot;

</span><span style="color: blue">#region </span><span style="color: black">functions - feel free to move to a separate file

</span><span style="color: blue">Function </span><span style="color: #5f9ea0">DeleteVhd
</span><span style="color: black">{
    </span><span style="color: blue">Param </span><span style="color: black">(</span><span style="color: purple">$pathToVhd</span><span style="color: black">)
    </span><span style="color: green"># delete the disk that was added if it exists
    </span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: #5f9ea0">test-path -path </span><span style="color: purple">$pathToVhd</span><span style="color: black">)
    {
        </span><span style="color: #5f9ea0">Remove-Item -Path </span><span style="color: purple">$pathToVhd </span><span style="color: #5f9ea0">-Force
    </span><span style="color: black">}
}

</span><span style="color: blue">#endregion

</span><span style="color: green"># delete the VHD if it already exists
</span><span style="color: #5f9ea0">DeleteVhd </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmName.vhd&quot;

</span><span style="color: green"># delete the VM if it already exists
</span><span style="color: black">Remove-VM -vm </span><span style="color: purple">$vmName </span><span style="color: black">-server </span><span style="color: purple">$server

</span><span style="color: green"># create a new virtual machine
</span><span style="color: purple">$vm </span><span style="color: red">= </span><span style="color: black">New-VM </span><span style="color: purple">$vmName </span><span style="color: black">-server </span><span style="color: purple">$server

</span><span style="color: green"># get the vm
</span><span style="color: purple">$vm </span><span style="color: red">= </span><span style="color: black">Get-VM </span><span style="color: purple">$vmName

</span><span style="color: green"># set cpu count
</span><span style="color: black">Set-VMCPUCount </span><span style="color: purple">$vm </span><span style="color: black">2 -server </span><span style="color: purple">$server

</span><span style="color: green"># set memory size
</span><span style="color: black">Set-VMMemory </span><span style="color: purple">$vm </span><span style="color: black">2 -memory 4GB -server </span><span style="color: purple">$server

</span><span style="color: green"># get VM Nics available
</span><span style="color: purple">$vmNics </span><span style="color: red">= </span><span style="color: black">Get-VMNic -server </span><span style="color: purple">$server </span><span style="color: black">-vmbus -legacy
</span><span style="color: purple">$vmNicSwitchList </span><span style="color: red">= </span><span style="color: #5f9ea0">New-Object </span><span style="color: maroon">System.Collections.ArrayList

</span><span style="color: green"># get VM Nic Switch available for each VM Nic and add it to our list
</span><span style="color: blue">foreach </span><span style="color: black">(</span><span style="color: purple">$vmNic </span><span style="color: blue">in </span><span style="color: purple">$vmNics</span><span style="color: black">)
{
    </span><span style="color: purple">$vmSwitchElementName </span><span style="color: red">= </span><span style="color: black">(Get-VMNicSwitch </span><span style="color: purple">$vmNic</span><span style="color: black">).ElementName
    </span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">.Contains(</span><span style="color: purple">$vmSwitchElementName</span><span style="color: black">) </span><span style="color: red">-ne </span><span style="color: blue">$true</span><span style="color: black">)
    {
        </span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">.Add(</span><span style="color: purple">$vmSwitchElementName</span><span style="color: black">)
    }
}

</span><span style="color: green"># Use the first available VM Nic Switch - this assumes 
# I do not create more than on per each environment.
</span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">.Count </span><span style="color: red">-gt </span><span style="color: black">0)
{
    </span><span style="color: purple">$vmVirtualSwitch </span><span style="color: red">= </span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">[0]
}

</span><span style="color: green"># add a legacy network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch </span><span style="color: black">-legacy

</span><span style="color: green"># add a default VMBus (non-legacy) network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch

</span><span style="color: green"># add the hard drive to the VM
</span><span style="color: purple">$parent </span><span style="color: red">= </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmParent.vhd&quot;
</span><span style="color: purple">$vhdPath </span><span style="color: red">= </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmName.vhd&quot;
</span><span style="color: black">Add-VMNewHardDisk –vm </span><span style="color: purple">$vm </span><span style="color: black">-controllerID 0 -lun 0 -vhdpath </span><span style="color: purple">$vhdPath </span><span style="color: black">-parent </span><span style="color: purple">$parent

</span><span style="color: green"># get the VM to see if a disk is attached to it, if it is not, then it failed
</span><span style="color: purple">$disks </span><span style="color: red">= </span><span style="color: black">Get-VMDisk -vm </span><span style="color: purple">$vm
$count </span><span style="color: red">= </span><span style="color: black">1

</span><span style="color: green"># if the disk was not successfully added, try and add it again
</span><span style="color: blue">while </span><span style="color: black">(</span><span style="color: purple">$disks </span><span style="color: red">-eq </span><span style="color: purple">$null </span><span style="color: red">-and </span><span style="color: purple">$count </span><span style="color: red">-le </span><span style="color: black">5)
{
    </span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;RETRY $count - The disk was not properly added. Attempting to retry.&quot;
    
    </span><span style="color: green"># delete the disk that was added
    </span><span style="color: #5f9ea0">DeleteVhd </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmName.vhd&quot;
    
    </span><span style="color: black">Add-VMNewHardDisk –vm </span><span style="color: purple">$vm </span><span style="color: black">-controllerID 0 -lun 0 -vhdpath </span><span style="color: purple">$vhdPath </span><span style="color: black">-parent </span><span style="color: purple">$parent
    
    $disks </span><span style="color: red">= </span><span style="color: black">Get-VMDisk -vm </span><span style="color: purple">$vm
    $count</span><span style="color: red">++
</span><span style="color: black">}

</span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: purple">$disks </span><span style="color: red">-eq </span><span style="color: purple">$null</span><span style="color: black">)
{
    </span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;Operation failed to create this virtual machine. Contact an admin.&quot;
</span><span style="color: black">}
</span><span style="color: blue">else
</span><span style="color: black">{
    </span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;Operation completed successfully. Attempting to start the VM.&quot;
    </span><span style="color: black">Start-VM -vm </span><span style="color: purple">$vm </span><span style="color: black">-wait
}</span></pre>
<a href="http://11011.net/software/vspaste"></a>

<p>I have found that the VM creation is not consistently successful on the first pass, so I have added the while loop. Since adding that, I have not had any issues.</p>

<p>I hope these help. They should be easy to change if you prefer snapshots versus differencing disks. Thanks to James O’Neill for creating this library. It makes administering Hyper-V much easier. It is available via <a title="CodePlex" href="http://www.codeplex.com/" target="_blank">CodePlex</a>, where the latest release, updates, and forum support can be found. </p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Installing Windows 7</title>
		<link>http://elegantcode.com/2009/02/09/installing-windows-7/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=installing-windows-7</link>
		<comments>http://elegantcode.com/2009/02/09/installing-windows-7/#comments</comments>
		<pubDate>Mon, 09 Feb 2009 21:14:36 +0000</pubDate>
		<dc:creator>Alex Mueller</dc:creator>
				<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Operating Systems]]></category>
		<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/02/09/installing-windows-7/</guid>
		<description><![CDATA[The short story is this. If you are accessing Windows 7 from your MSDN subscriptions, save yourself time and frustration by installing the Windows 7 Beta, not the Windows 7 Beta Checked Build. See available downloads here. This past weekend, I decided to upgrade my work laptop from Vista Enterprise to Windows 7 Ultimate Beta. [...]]]></description>
			<content:encoded><![CDATA[<p>The short story is this. If you are accessing Windows 7 from your MSDN subscriptions, save yourself time and frustration by installing the Windows 7 Beta, not the Windows 7 Beta Checked Build. <a href="http://msdn.microsoft.com/en-us/subscriptions/cc137115.aspx" target="_blank">See available downloads here</a>.</p>  <p>This past weekend, I decided to upgrade my work laptop from Vista Enterprise to Windows 7 Ultimate Beta. I was unable to upgrade from Vista Enterprise to 7 Ultimate because that action is not supported. I then tried to upgrade from Enterprise to 7 Enterprise, but I was unable to upgrade from a staged build to a non-staged build. I decided to repave entirely, choosing Windows 7 Ultimate Beta, and I tried to do all of this on a Friday afternoon, two hours before leaving.</p>  <p>I installed Windows 7 Beta Checked Build (x86) - DVD (English), last updated on January 14, 2009,&#160; from my MSDN subscription. I did not install an internal build. Instead, I decided to go with what is publicly available via MSDN. </p>  <p>Why did I go with a <a href="http://msdn.microsoft.com/en-us/library/ms792442.aspx" target="_blank">Checked Build</a>? Because I failed to read the details describing it. What it cost me in time and frustration, I gain in valuable learning experiences. So it was not a total loss. I received a number of buggy issues with the checked build, mainly the inability for Windows Update to properly download all of my necessary updates, including my video drivers and smart card reader, where the latter enables me to remotely access my work domain. </p>  <p>I gave up and decided to download and install the Windows 7 Beta – DVD (English). Everything works great. I was able to get online, download all of my updates, and connect to my work domain. No issues found so far, and no annoying assertion error popups. </p>  <p>My favorite Windows 7 feature so far (non-UI related) is that PowerShell 2.0 is installed by default. PowerShell 2.0 provides more functionality for remoting, among other enhancements.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/02/09/installing-windows-7/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>PowerShell Documentation</title>
		<link>http://elegantcode.com/2008/12/17/powershell-documentation/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-documentation</link>
		<comments>http://elegantcode.com/2008/12/17/powershell-documentation/#comments</comments>
		<pubDate>Wed, 17 Dec 2008 20:36:54 +0000</pubDate>
		<dc:creator>Alex Mueller</dc:creator>
				<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/12/17/powershell-documentation/</guid>
		<description><![CDATA[PowerShell documentation, you are too honest. Get-Help Remove-Item -Full As I was retrieving information on "Remove-Item," this is what I came across. There is more detail beyond what I am showing, but pay attention to what is bolded. NAME&#160;&#160;&#160; Remove-Item SYNOPSIS&#160;&#160;&#160; Deletes the specified items. SYNTAX&#160;&#160;&#160; Remove-Item [-path] &#60;string[]&#62; [-recurse] [-force] [-include &#60;string[]&#62;] [-&#160;&#160;&#160; exclude [...]]]></description>
			<content:encoded><![CDATA[<p>PowerShell documentation, you are too honest. </p> <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:F2210F5F-69EB-4d4c-AFF7-B8A050E9CC72:2ed0ad7a-f3da-498d-a817-1bb0c8b8f8c3" class="wlWriterSmartContent"><pre  style="width:100%;;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #000000;">Get</span><span style="color: #000000;">-</span><span style="color: #000000;">Help Remove</span><span style="color: #000000;">-</span><span style="color: #000000;">Item </span><span style="color: #000000;">-</span><span style="color: #000000;">Full</span></div></pre></div>
<p>As I was retrieving information on "Remove-Item," this is what I came across. There is more detail beyond what I am showing, but pay attention to what is <strong>bolded</strong>. </p>
<blockquote>
<p>NAME<br>&nbsp;&nbsp;&nbsp; Remove-Item 
<p>SYNOPSIS<br>&nbsp;&nbsp;&nbsp; Deletes the specified items. 
<p>SYNTAX<br>&nbsp;&nbsp;&nbsp; Remove-Item [-path] &lt;string[]&gt; [-recurse] [-force] [-include &lt;string[]&gt;] [-<br>&nbsp;&nbsp;&nbsp; exclude &lt;string[]&gt;] [-filter &lt;string&gt;] [-credential &lt;PSCredential&gt;] [-whatI<br>&nbsp;&nbsp;&nbsp; f] [-confirm] [&lt;CommonParameters&gt;] 
<p>&nbsp;&nbsp;&nbsp; Remove-Item [-literalPath] &lt;string[]&gt; [-recurse] [-force] [-include &lt;string<br>&nbsp;&nbsp;&nbsp; []&gt;] [-exclude &lt;string[]&gt;] [-filter &lt;string&gt;] [-credential &lt;PSCredential&gt;]<br>&nbsp;&nbsp;&nbsp; [-whatIf] [-confirm] [&lt;CommonParameters&gt;] 
<p>DETAILED DESCRIPTION<br>&nbsp;&nbsp;&nbsp; The Remove-Item cmdlet deletes one or more items. Because it is supported b<br>&nbsp;&nbsp;&nbsp; y many providers, it can delete many different types of items, including fi<br>&nbsp;&nbsp;&nbsp; les, directories, registry keys, variables, aliases, certificates, and func<br>&nbsp;&nbsp;&nbsp; tions. 
<p>PARAMETERS<br>&nbsp;&nbsp;&nbsp; -path &lt;string[]&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Specifies a path to the items being removed. Wildcards are permitted. T<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; he parameter name ("-Path") is optional. 
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Required?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; true<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Position?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 1<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Default value&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; N/A - The path must be specified<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept pipeline input?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; true (ByValue, ByPropertyName)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept wildcard characters?&nbsp; true 
<p>&nbsp;&nbsp;&nbsp; -recurse &lt;SwitchParameter&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Deletes the items in the specified locations and in all child items of<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; the locations. 
<p><strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; The Recurse parameter in this cmdlet does not work properly. </strong>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Required?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; false<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Position?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; named<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Default value&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; False<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept pipeline input?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; false<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept wildcard characters?&nbsp; false 
<p><strong></strong>&nbsp;</p></blockquote>
<p>"Hmmm... Am I feeling lucky? Ahhh, what the hell, let's do it."</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:F2210F5F-69EB-4d4c-AFF7-B8A050E9CC72:a3ee0edf-63f8-43fc-a4fb-22c6277656f8" class="wlWriterSmartContent"><pre  style="width:100%;;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #000000;">Remove</span><span style="color: #000000;">-</span><span style="color: #000000;">Item </span><span style="color: #800000;">&quot;</span><span style="color: #800000;">C:\</span><span style="color: #800000;">&quot;</span><span style="color: #000000;"> </span><span style="color: #000000;">-</span><span style="color: #000000;">Recurse</span></div></pre></div>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/12/17/powershell-documentation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Automate Daily Tasks with PowerShell</title>
		<link>http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-management-library-for-hyper-v</link>
		<comments>http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/#comments</comments>
		<pubDate>Wed, 25 Mar 2009 21:46:16 +0000</pubDate>
		<dc:creator>Alex Mueller</dc:creator>
				<category><![CDATA[Hyper-V]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Tools and Utilities]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/</guid>
		<description><![CDATA[I am always looking for tools to allow me to do more by doing less. Administering Hyper-V with PowerShell can be tedious. James O’Neill’s PowerShell Management Library for Hyper-V is a great tool to improve automation of Hyper-V management using PowerShell. As a tester, I am constantly creating new environments, installing our product, taking snapshots, [...]]]></description>
			<content:encoded><![CDATA[<p>I am always looking for tools to allow me to do more by doing less. Administering Hyper-V with PowerShell can be tedious. James O’Neill’s <a href="http://pshyperv.codeplex.com/" target="_blank">PowerShell Management Library for Hyper-V</a> is a great tool to improve automation of Hyper-V management using PowerShell.</p>  <p>As a tester, I am constantly creating new environments, installing our product, taking snapshots, ect. Doing this by hand is a waste of time in my opinion. Doing this with a script makes life easier and frees up my time. </p>  <p>Typically, I prefer to create is to create one VM and to have other VMs inherit from that base image. My second VM (the first child to inherit from the base), I will install daily builds of our product. I will then create a third child, which I use a sandbox. I can easily delete it and recreate as needed without having to install our product over again. I have not consistently found success with using snapshots, so I prefer to use differencing disks. The examples below use differencing disks. </p>  <p>This first code block shows how I am using the PowerShell management library to simply the creation of a base VM. There is nothing magic about it. It’s pretty strait-forward. I create a VM, give it a name, set the CPU count, memory size, network adapters, hard drive, and DVD drive.</p>  <pre class="code"><span style="color: purple">$server </span><span style="color: red">= </span><span style="color: maroon">&quot;my-dev-server&quot;
</span><span style="color: purple">$vmName </span><span style="color: red">= </span><span style="color: maroon">&quot;TestParentVM&quot;
</span><span style="color: purple">$vmVirtualSwitch </span><span style="color: red">= </span><span style="color: maroon">&quot;My Virtual Network&quot;

</span><span style="color: green"># create a new virtual machine
</span><span style="color: purple">$vm </span><span style="color: red">= </span><span style="color: black">New-VM </span><span style="color: purple">$vmName </span><span style="color: black">-server </span><span style="color: purple">$server

</span><span style="color: green"># set cpu count
</span><span style="color: black">Set-VMCPUCount </span><span style="color: purple">$vm </span><span style="color: black">2 -server </span><span style="color: purple">$server

</span><span style="color: green"># set memory size
</span><span style="color: black">Set-VMMemory </span><span style="color: purple">$vm </span><span style="color: black">2 -memory 4GB -server </span><span style="color: purple">$server

</span><span style="color: green"># add a legacy network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch </span><span style="color: black">-legacy

</span><span style="color: green"># add a default VMBus (non-legacy) network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch

</span><span style="color: green"># add the hard drive to the VM
</span><span style="color: black">Add-VMNewHardDisk –vm </span><span style="color: purple">$vm </span><span style="color: black">-controllerID 0 -lun 0 -vhdpath </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)\$vmName.vhd&quot; </span><span style="color: black">-size 20GB

</span><span style="color: green"># add the DVD with bootup ISO
</span><span style="color: black">Add-VMDRIVE –vm </span><span style="color: purple">$vm </span><span style="color: black">1 1 -server </span><span style="color: purple">$server </span><span style="color: black">-DVD 

</span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;Operation complete.&quot;</span></pre>
<a href="http://11011.net/software/vspaste"></a>

<p>The next code block will create a differencing disk pointing to the parent created in the previous example. I create the usual, VM, CPU count, ect. What makes this a differencing disk is how the VHD is created by specifying the parent. I do some cleanup in this routine by deleting any previously created VMs or VHDs, and I loop through the creation a failure preventative. </p>

<pre class="code"><span style="color: purple">$server </span><span style="color: red">= </span><span style="color: maroon">&quot;my-dev-server&quot;
</span><span style="color: purple">$vmName </span><span style="color: red">= </span><span style="color: maroon">&quot;TestChildVM&quot;
</span><span style="color: purple">$vmParent </span><span style="color: red">= </span><span style="color: maroon">&quot;TestParentVM&quot;
</span><span style="color: purple">$vmVirtualSwitch </span><span style="color: red">= </span><span style="color: maroon">&quot;My Virtual Network&quot;

</span><span style="color: blue">#region </span><span style="color: black">functions - feel free to move to a separate file

</span><span style="color: blue">Function </span><span style="color: #5f9ea0">DeleteVhd
</span><span style="color: black">{
    </span><span style="color: blue">Param </span><span style="color: black">(</span><span style="color: purple">$pathToVhd</span><span style="color: black">)
    </span><span style="color: green"># delete the disk that was added if it exists
    </span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: #5f9ea0">test-path -path </span><span style="color: purple">$pathToVhd</span><span style="color: black">)
    {
        </span><span style="color: #5f9ea0">Remove-Item -Path </span><span style="color: purple">$pathToVhd </span><span style="color: #5f9ea0">-Force
    </span><span style="color: black">}
}

</span><span style="color: blue">#endregion

</span><span style="color: green"># delete the VHD if it already exists
</span><span style="color: #5f9ea0">DeleteVhd </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)\$vmName.vhd&quot;

</span><span style="color: green"># delete the VM if it already exists
</span><span style="color: black">Remove-VM -vm </span><span style="color: purple">$vmName </span><span style="color: black">-server </span><span style="color: purple">$server

</span><span style="color: green"># create a new virtual machine
</span><span style="color: purple">$vm </span><span style="color: red">= </span><span style="color: black">New-VM </span><span style="color: purple">$vmName </span><span style="color: black">-server </span><span style="color: purple">$server

</span><span style="color: green"># get the vm
</span><span style="color: purple">$vm </span><span style="color: red">= </span><span style="color: black">Get-VM </span><span style="color: purple">$vmName

</span><span style="color: green"># set cpu count
</span><span style="color: black">Set-VMCPUCount </span><span style="color: purple">$vm </span><span style="color: black">2 -server </span><span style="color: purple">$server

</span><span style="color: green"># set memory size
</span><span style="color: black">Set-VMMemory </span><span style="color: purple">$vm </span><span style="color: black">2 -memory 4GB -server </span><span style="color: purple">$server

</span><span style="color: green"># get VM Nics available
</span><span style="color: purple">$vmNics </span><span style="color: red">= </span><span style="color: black">Get-VMNic -server </span><span style="color: purple">$server </span><span style="color: black">-vmbus -legacy
</span><span style="color: purple">$vmNicSwitchList </span><span style="color: red">= </span><span style="color: #5f9ea0">New-Object </span><span style="color: maroon">System.Collections.ArrayList

</span><span style="color: green"># get VM Nic Switch available for each VM Nic and add it to our list
</span><span style="color: blue">foreach </span><span style="color: black">(</span><span style="color: purple">$vmNic </span><span style="color: blue">in </span><span style="color: purple">$vmNics</span><span style="color: black">)
{
    </span><span style="color: purple">$vmSwitchElementName </span><span style="color: red">= </span><span style="color: black">(Get-VMNicSwitch </span><span style="color: purple">$vmNic</span><span style="color: black">).ElementName
    </span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">.Contains(</span><span style="color: purple">$vmSwitchElementName</span><span style="color: black">) </span><span style="color: red">-ne </span><span style="color: blue">$true</span><span style="color: black">)
    {
        </span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">.Add(</span><span style="color: purple">$vmSwitchElementName</span><span style="color: black">)
    }
}

</span><span style="color: green"># Use the first available VM Nic Switch - this assumes 
# I do not create more than on per each environment.
</span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">.Count </span><span style="color: red">-gt </span><span style="color: black">0)
{
    </span><span style="color: purple">$vmVirtualSwitch </span><span style="color: red">= </span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">[0]
}

</span><span style="color: green"># add a legacy network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch </span><span style="color: black">-legacy

</span><span style="color: green"># add a default VMBus (non-legacy) network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch

</span><span style="color: green"># add the hard drive to the VM
</span><span style="color: purple">$parent </span><span style="color: red">= </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)\$vmParent.vhd&quot;
</span><span style="color: purple">$vhdPath </span><span style="color: red">= </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)\$vmName.vhd&quot;
</span><span style="color: black">Add-VMNewHardDisk –vm </span><span style="color: purple">$vm </span><span style="color: black">-controllerID 0 -lun 0 -vhdpath </span><span style="color: purple">$vhdPath </span><span style="color: black">-parent </span><span style="color: purple">$parent

</span><span style="color: green"># get the VM to see if a disk is attached to it, if it is not, then it failed
</span><span style="color: purple">$disks </span><span style="color: red">= </span><span style="color: black">Get-VMDisk -vm </span><span style="color: purple">$vm
$count </span><span style="color: red">= </span><span style="color: black">1

</span><span style="color: green"># if the disk was not successfully added, try and add it again
</span><span style="color: blue">while </span><span style="color: black">(</span><span style="color: purple">$disks </span><span style="color: red">-eq </span><span style="color: purple">$null </span><span style="color: red">-and </span><span style="color: purple">$count </span><span style="color: red">-le </span><span style="color: black">5)
{
    </span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;RETRY $count - The disk was not properly added. Attempting to retry.&quot;
    
    </span><span style="color: green"># delete the disk that was added
    </span><span style="color: #5f9ea0">DeleteVhd </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)\$vmName.vhd&quot;
    
    </span><span style="color: black">Add-VMNewHardDisk –vm </span><span style="color: purple">$vm </span><span style="color: black">-controllerID 0 -lun 0 -vhdpath </span><span style="color: purple">$vhdPath </span><span style="color: black">-parent </span><span style="color: purple">$parent
    
    $disks </span><span style="color: red">= </span><span style="color: black">Get-VMDisk -vm </span><span style="color: purple">$vm
    $count</span><span style="color: red">++
</span><span style="color: black">}

</span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: purple">$disks </span><span style="color: red">-eq </span><span style="color: purple">$null</span><span style="color: black">)
{
    </span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;Operation failed to create this virtual machine. Contact an admin.&quot;
</span><span style="color: black">}
</span><span style="color: blue">else
</span><span style="color: black">{
    </span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;Operation completed successfully. Attempting to start the VM.&quot;
    </span><span style="color: black">Start-VM -vm </span><span style="color: purple">$vm </span><span style="color: black">-wait
}</span></pre>
<a href="http://11011.net/software/vspaste"></a>

<p>I have found that the VM creation is not consistently successful on the first pass, so I have added the while loop. Since adding that, I have not had any issues.</p>

<p>I hope these help. They should be easy to change if you prefer snapshots versus differencing disks. Thanks to James O’Neill for creating this library. It makes administering Hyper-V much easier. It is available via <a title="CodePlex" href="http://www.codeplex.com/" target="_blank">CodePlex</a>, where the latest release, updates, and forum support can be found. </p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Elegant Code &#187; PowerShell</title>
	<atom:link href="http://elegantcode.com/category/microsoft/powershell/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Silverlight Profiling PowerShell helper.</title>
		<link>http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=silverlight-profiling-powershell-helper</link>
		<comments>http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/#comments</comments>
		<pubDate>Sat, 15 May 2010 16:47:22 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/</guid>
		<description><![CDATA[I was playing around with some Silverlight profiling the other night to see if I could find any obvious issues with my open source project StatLight and wound up writing a little script in PowerShell I hoped someone might find helpful. But I didn’t know you could profile a Silverlight app. I didn’t until I [...]]]></description>
			<content:encoded><![CDATA[<p>I was playing around with some Silverlight profiling the other night to see if I could find any obvious issues with my open source project <a href="http://statlight.net" target="_blank">StatLight</a> and wound up writing a little script in PowerShell I hoped someone might find helpful.</p>  <h4>But I didn’t know you could profile a Silverlight app.</h4>  <p>I didn’t until I started doing some digging online. Now, the Silverlight profiling story (at least from what I’ve seen/tried) is not near the easy of say <a href="http://www.red-gate.com/products/ants_performance_profiler/index.htm">Redgate ANTS Performance Profiler</a>. However, it’s do-able. (And with this helper script – hopefully a little simpler?)</p>  <h4>How can I profile a Silverlight Application?</h4>  <p>I would recommend you read the following blog, which explains one way of doing it very well.</p>  <p><a title="http://blogs.msdn.com/profiler/archive/2010/04/26/vs2010-silverlight-4-profiling.aspx" href="http://blogs.msdn.com/profiler/archive/2010/04/26/vs2010-silverlight-4-profiling.aspx">http://blogs.msdn.com/profiler/archive/2010/04/26/vs2010-silverlight-4-profiling.aspx</a></p>  <h4>So… what’s this script for?</h4>  <p>If you read the blog above, or have done this before, then you probably noticed that there was quite a series of commands you had to execute before you could wind up with a performance report. </p>  <p>I threw together a quick little PowerShell script in an attempt to automate smooth out the process.</p>  <h4>Hot do I use it?</h4>  <ol>   <li>Download the script &amp; save it somewhere. <a href="http://github.com/staxmanade/Scripts/blob/master/SilverlightProfiler.ps1"><strong>http://github.com/staxmanade/Scripts/blob/master/SilverlightProfiler.ps1</strong></a> </li>    <li>Open the PowerShell console. cd to the directory your xap/assemblies are stored.      <br />(EX: {myProject}\Bin\Debug\ ) </li>    <li>Execute:      <br />{pathToScript}\SilverlightProfiler.ps1 -urlPath &quot;{myProject}\Bin\Debug\TestPage.html&quot; </li>    <li>When your done profiling press enter to signal that your done.      <p></p> Once complete, it will print the location your profiling report was saved. You can then open it with Visual Studio.</li> </ol>  <h5>Couple of disclaimers.</h5>  <ul>   <li>Some paths are hard-coded to my x86 machine. </li>    <li>I had troubles running the built in visual studio .bat files (from powershell) that are supposed to set the environment variables. So I extracted out what vars I could find to make it work. </li>    <li>I’m not a profiling expert – just hacked this together to get it to work for me.</li> </ul>  <p>I hope this is useful, and if you know of a better way, I’m always interested in hearing your feedback.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Powershell: Load assembly without locking file.</title>
		<link>http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-load-assembly-without-locking-file</link>
		<comments>http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/#comments</comments>
		<pubDate>Wed, 23 Dec 2009 05:40:23 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/</guid>
		<description><![CDATA[I have a set of PowerShell build scripts and ran into a case where I needed to load an assembly (to get the assembly’s version) and still (at a later time) work with the assembly file on disk. A typical way to load an assembly within PowerShell is to use the Assembly.LoadFrom(filePath) # Powershell [System.Reflection.Assembly]::LoadFrom($assemblyPath) [...]]]></description>
			<content:encoded><![CDATA[<p>I have a set of PowerShell build scripts and ran into a case where I needed to load an assembly (to get the assembly’s version) and still (at a later time) work with the assembly file on disk.</p>  <p>A typical way to load an assembly within PowerShell is to use the Assembly.LoadFrom(filePath)</p>  <blockquote>   <p># Powershell</p>    <p>[System.Reflection.Assembly]::LoadFrom($assemblyPath)</p> </blockquote>  <p><a href="http://elegantcode.com/wp-content/uploads/2009/12/image9.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://elegantcode.com/wp-content/uploads/2009/12/image_thumb9.png" width="690" height="391" /></a> </p>  <p>Except the problem with this (in my case) was it would <strong>lock the file for the lifespan of the PowerShell console instance</strong>. I didn’t want to have to close and re-open the PowerShell console every time I need to run a build so there had to be a work-around for this.</p>  <p>After searching the web for a solution, I couldn’t find anything that was “easy” and worth the effort to get it to work.</p>  <blockquote>   <p>EX: One solution was to create a new AppDomain, do the necessary work and the close the AppDomain which would release the lock on the file.</p>    <p>I’ve never done this myself, and even thought there is example code out there to get this accomplished, it just seemed over the top for what I was trying to do, and back to my previous criteria it wasn’t “worth the effort to get it to work”</p> </blockquote>  <p>Then I remembered in a previous life I used an overload that took an array of bytes to load the an assembly.</p>  <blockquote>   <p>[System.Reflection.Assembly]::Load($assemblyBytes)</p> </blockquote>  <p>After spiking it in PowerShell with the below test. I was quite happy with the solution, so I thought I’d throw it out there.</p>  <p>Just stream the assembly from disk into a byte array manually, and call assembly load from there.</p>  <p>Here’s my test case which shows that the file is not locked after it was loaded into the PowerShell runtime</p>  <pre>$file = &quot;.\Moq.dll&quot;
$tempFileName = &quot;.\Moq-Renamed.dll&quot;

$fileStream = ([System.IO.FileInfo] (Get-Item $file)).OpenRead();
$assemblyBytes = new-object byte[] $fileStream.Length
$fileStream.Read($assemblyBytes, 0, $fileStream.Length);
$fileStream.Close();

$assemblyLoaded = [System.Reflection.Assembly]::Load($assemblyBytes);

# notice that we can move the file on disk after 
# it's loaded into the powershell runtime
Move-Item $file $tempFileName
Move-Item $tempFileName $file 

# and display the assembly information to show we still have it in memory
echo $assemblyLoaded</pre>

<p>After that test passed, and the main reason I wanted to do this, I wrote the “get-assembly-version” PowerShell function.</p>

<pre><strike>function get-assembly-version() {
    param([string] $file)
    
    # load the assembly bytes quickly - as to not lock the file for too long
    $fileStream = ([System.IO.FileInfo] (Get-Item $file)).OpenRead()
    $assemblyBytes = new-object byte[] $fileStream.Length
    $fileStream.Read($assemblyBytes, 0, $fileStream.Length) | Out-Null #out null this because this function should only return the version &amp; this call was outputting some garbage number
    $fileStream.Close()
    
    # return the version of the assembly
    [System.Reflection.Assembly]::Load($assemblyBytes).GetName().Version;
}

$version = get-assembly-version(&quot;.\Moq.dll&quot;)

echo &quot;Loaded v$($version.Major).$($version.Minor).$($version.Build).$($version.Revision) version of $file&quot;</strike></pre>
Hope this helps someone out there! 

<p></p>

<p>&#160;</p>

<p><strong>UPDATE:</strong></p>

<p><a href="http://achuebrigens.wordpress.com">Martin</a> commented below on a much better solution to the assembly version info problem. Amazing how complicated we can make things if we don’t know the path.</p>

<pre>
function get-assembly-version() {
    param([string] $file)
    
    $version = [System.Reflection.AssemblyName]::GetAssemblyName($file).Version;
    
    #format the version and output it...
    $version
}</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Integration Test Brought to you by Powershell &amp; NUnit &#8211; with a Little Specification Syntax for Flavoring</title>
		<link>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring</link>
		<comments>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/#comments</comments>
		<pubDate>Mon, 26 Oct 2009 05:00:40 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/</guid>
		<description><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about Fluent Specification Extensions in a past blog. Recently I wanted to execute a PowerShell script [...]]]></description>
			<content:encoded><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about <a href="http://staxmanade.blogspot.com/2009/02/fluent-specification-extensions.html">Fluent Specification Extensions</a> in a past blog.

Recently I wanted to execute a PowerShell script to do some automated <a href="http://en.wikipedia.org/wiki/Functional_testing">functional testing</a>. I wanted to execute an application and apply some assertions on the output of the software(basically running a console app, parse the xml output and assert on values in the output).
<blockquote>FYI: I’m very new to PowerShell, so any suggestions on how I implemented the below are welcome…</blockquote>
I’ve seen a couple examples of writing test assertions in PowerShell out there. One example is <a href="http://www.psunit.org/">PSUnit</a>; however, this seemed a little heavy for my needs and not quite the syntactic sugar I was looking for.

Besides the syntax flavor I was desiring, another thing I wanted to do was leverage the power of NUnit.Framework’s assertion capabilities. I like the error messages generated when strings and other objects fail the assertion.
<h5>Examples of end result ShouldLookLike()…</h5>
$true.ShouldBeTrue()
$false.ShouldBeFalse()
"a".ShouldEqual("a")
"a".ShouldNotEqual("b")
<h5><strong>Step 1</strong>: Figure out how to write a C# style <a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx">extension method</a> in PowerShell.</h5>
<blockquote>I found a great blog post describing how to extend any PowerShell object to add extension methods.

<a href="http://bartdesmet.net/blogs/bart/archive/2007/09/06/extension-methods-in-windows-powershell.aspx">Extension Methods in Windows PowerShell</a></blockquote>
In short, to extend types in PowerShell leveraging the <a href="http://msdn.microsoft.com/en-us/library/ms714419(VS.85).aspx">Extended Type System</a>, you need to define them in an xml file and import the method definitions into the PowerShell runtime instance.

Below is PowerShell XML definition for my NUnit Specification Extensions.
<pre class="brush: xml;">&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;Types&gt;
    &lt;Type&gt;
        &lt;Name&gt;System.Object&lt;/Name&gt;
        &lt;Members&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeFalse&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsFalse($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeTrue&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsTrue($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldNotEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreNotEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
        &lt;/Members&gt;
    &lt;/Type&gt;
&lt;/Types&gt;</pre>
<h4></h4>
Take the above XML and save it to a file…
<blockquote>NOTE: the file HAS to be saved with the extension <strong>.ps1xml</strong>

Ex: NunitSpecificationPowerShellExtensions<strong>.ps1xml</strong></blockquote>
<h4></h4>
<h5>Step 2: Load the extended type definition into the PowerShell runtime.</h5>
Once you’ve saved the XML extended types to a file, you need to load it into the PowerShell runtime by executing the command below.
<blockquote>
Update-TypeData -PrependPath NunitSpecificationPowerShellExtensions.ps1xml</blockquote>
Before executing the above statement…Let’s quickly look at a System.String’s members and properties – just to show you what the extension methods look like when applied inside of the runtime.<a href="http://elegantcode.com/wp-content/uploads/2009/10/image3.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb2.png" border="0" alt="image" width="586" height="479" /></a>

After executing the Update-TypeData command you’ll notice there are a number of “ScriptMethod” MemberTypes added to the object.

<a href="http://elegantcode.com/wp-content/uploads/2009/10/image4.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb3.png" border="0" alt="image" width="600" height="580" /></a>

Now if you try to execute one of those newly added extension methods, you may get the following error…

PS C:\&gt; $testVar.<strong>ShouldEqual</strong>("hello world")

Exception calling "ShouldEqual" with "1" argument(s): "<strong>Unable to find type [NUnit.Framework.Assert]: make sure that the

assembly containing this type is loaded.</strong>"

At line:1 char:21

+ $testVar.ShouldEqual &lt;&lt;&lt;&lt; ("hello world")

+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

+ FullyQualifiedErrorId : ScriptMethodRuntimeException

This is because we need to load the NUnit.Framework assembly into the runtime before we can leverage the extension methods.
<blockquote>[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null</blockquote>
Now that the extension methods have been defined and loaded into the runtime, NUnit.Framework is loaded, we can now use the methods on any object that inherits from System.Object (which, as far as I know, is everything in PowerShell).

And now, everything you need in one script (if you have the xml extended type file saved somewhere…)
<pre>#
# Update-TypeData -prependPath C:\Code\NunitSpecificationPowerShellExtensions.ps1xml
#

[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null

$true.ShouldBeTrue()

$false.ShouldBeFalse()

"a".ShouldEqual("a")

"a".ShouldNotEqual("b")</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>PowerShell Management Library for Hyper-V</title>
		<link>http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-management-library-for-hyper-v</link>
		<comments>http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/#comments</comments>
		<pubDate>Wed, 25 Mar 2009 21:46:16 +0000</pubDate>
		<dc:creator>Alex Mueller</dc:creator>
				<category><![CDATA[Hyper-V]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Tools and Utilities]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/</guid>
		<description><![CDATA[I am always looking for tools to allow me to do more by doing less. Administering Hyper-V with PowerShell can be tedious. James O’Neill’s PowerShell Management Library for Hyper-V is a great tool to improve automation of Hyper-V management using PowerShell. As a tester, I am constantly creating new environments, installing our product, taking snapshots, [...]]]></description>
			<content:encoded><![CDATA[<p>I am always looking for tools to allow me to do more by doing less. Administering Hyper-V with PowerShell can be tedious. James O’Neill’s <a href="http://pshyperv.codeplex.com/" target="_blank">PowerShell Management Library for Hyper-V</a> is a great tool to improve automation of Hyper-V management using PowerShell.</p>  <p>As a tester, I am constantly creating new environments, installing our product, taking snapshots, ect. Doing this by hand is a waste of time in my opinion. Doing this with a script makes life easier and frees up my time. </p>  <p>Typically, I prefer to create is to create one VM and to have other VMs inherit from that base image. My second VM (the first child to inherit from the base), I will install daily builds of our product. I will then create a third child, which I use a sandbox. I can easily delete it and recreate as needed without having to install our product over again. I have not consistently found success with using snapshots, so I prefer to use differencing disks. The examples below use differencing disks. </p>  <p>This first code block shows how I am using the PowerShell management library to simply the creation of a base VM. There is nothing magic about it. It’s pretty strait-forward. I create a VM, give it a name, set the CPU count, memory size, network adapters, hard drive, and DVD drive.</p>  <pre class="code"><span style="color: purple">$server </span><span style="color: red">= </span><span style="color: maroon">&quot;my-dev-server&quot;
</span><span style="color: purple">$vmName </span><span style="color: red">= </span><span style="color: maroon">&quot;TestParentVM&quot;
</span><span style="color: purple">$vmVirtualSwitch </span><span style="color: red">= </span><span style="color: maroon">&quot;My Virtual Network&quot;

</span><span style="color: green"># create a new virtual machine
</span><span style="color: purple">$vm </span><span style="color: red">= </span><span style="color: black">New-VM </span><span style="color: purple">$vmName </span><span style="color: black">-server </span><span style="color: purple">$server

</span><span style="color: green"># set cpu count
</span><span style="color: black">Set-VMCPUCount </span><span style="color: purple">$vm </span><span style="color: black">2 -server </span><span style="color: purple">$server

</span><span style="color: green"># set memory size
</span><span style="color: black">Set-VMMemory </span><span style="color: purple">$vm </span><span style="color: black">2 -memory 4GB -server </span><span style="color: purple">$server

</span><span style="color: green"># add a legacy network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch </span><span style="color: black">-legacy

</span><span style="color: green"># add a default VMBus (non-legacy) network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch

</span><span style="color: green"># add the hard drive to the VM
</span><span style="color: black">Add-VMNewHardDisk –vm </span><span style="color: purple">$vm </span><span style="color: black">-controllerID 0 -lun 0 -vhdpath </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmName.vhd&quot; </span><span style="color: black">-size 20GB

</span><span style="color: green"># add the DVD with bootup ISO
</span><span style="color: black">Add-VMDRIVE –vm </span><span style="color: purple">$vm </span><span style="color: black">1 1 -server </span><span style="color: purple">$server </span><span style="color: black">-DVD 

</span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;Operation complete.&quot;</span></pre>
<a href="http://11011.net/software/vspaste"></a>

<p>The next code block will create a differencing disk pointing to the parent created in the previous example. I create the usual, VM, CPU count, ect. What makes this a differencing disk is how the VHD is created by specifying the parent. I do some cleanup in this routine by deleting any previously created VMs or VHDs, and I loop through the creation a failure preventative. </p>

<pre class="code"><span style="color: purple">$server </span><span style="color: red">= </span><span style="color: maroon">&quot;my-dev-server&quot;
</span><span style="color: purple">$vmName </span><span style="color: red">= </span><span style="color: maroon">&quot;TestChildVM&quot;
</span><span style="color: purple">$vmParent </span><span style="color: red">= </span><span style="color: maroon">&quot;TestParentVM&quot;
</span><span style="color: purple">$vmVirtualSwitch </span><span style="color: red">= </span><span style="color: maroon">&quot;My Virtual Network&quot;

</span><span style="color: blue">#region </span><span style="color: black">functions - feel free to move to a separate file

</span><span style="color: blue">Function </span><span style="color: #5f9ea0">DeleteVhd
</span><span style="color: black">{
    </span><span style="color: blue">Param </span><span style="color: black">(</span><span style="color: purple">$pathToVhd</span><span style="color: black">)
    </span><span style="color: green"># delete the disk that was added if it exists
    </span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: #5f9ea0">test-path -path </span><span style="color: purple">$pathToVhd</span><span style="color: black">)
    {
        </span><span style="color: #5f9ea0">Remove-Item -Path </span><span style="color: purple">$pathToVhd </span><span style="color: #5f9ea0">-Force
    </span><span style="color: black">}
}

</span><span style="color: blue">#endregion

</span><span style="color: green"># delete the VHD if it already exists
</span><span style="color: #5f9ea0">DeleteVhd </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmName.vhd&quot;

</span><span style="color: green"># delete the VM if it already exists
</span><span style="color: black">Remove-VM -vm </span><span style="color: purple">$vmName </span><span style="color: black">-server </span><span style="color: purple">$server

</span><span style="color: green"># create a new virtual machine
</span><span style="color: purple">$vm </span><span style="color: red">= </span><span style="color: black">New-VM </span><span style="color: purple">$vmName </span><span style="color: black">-server </span><span style="color: purple">$server

</span><span style="color: green"># get the vm
</span><span style="color: purple">$vm </span><span style="color: red">= </span><span style="color: black">Get-VM </span><span style="color: purple">$vmName

</span><span style="color: green"># set cpu count
</span><span style="color: black">Set-VMCPUCount </span><span style="color: purple">$vm </span><span style="color: black">2 -server </span><span style="color: purple">$server

</span><span style="color: green"># set memory size
</span><span style="color: black">Set-VMMemory </span><span style="color: purple">$vm </span><span style="color: black">2 -memory 4GB -server </span><span style="color: purple">$server

</span><span style="color: green"># get VM Nics available
</span><span style="color: purple">$vmNics </span><span style="color: red">= </span><span style="color: black">Get-VMNic -server </span><span style="color: purple">$server </span><span style="color: black">-vmbus -legacy
</span><span style="color: purple">$vmNicSwitchList </span><span style="color: red">= </span><span style="color: #5f9ea0">New-Object </span><span style="color: maroon">System.Collections.ArrayList

</span><span style="color: green"># get VM Nic Switch available for each VM Nic and add it to our list
</span><span style="color: blue">foreach </span><span style="color: black">(</span><span style="color: purple">$vmNic </span><span style="color: blue">in </span><span style="color: purple">$vmNics</span><span style="color: black">)
{
    </span><span style="color: purple">$vmSwitchElementName </span><span style="color: red">= </span><span style="color: black">(Get-VMNicSwitch </span><span style="color: purple">$vmNic</span><span style="color: black">).ElementName
    </span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">.Contains(</span><span style="color: purple">$vmSwitchElementName</span><span style="color: black">) </span><span style="color: red">-ne </span><span style="color: blue">$true</span><span style="color: black">)
    {
        </span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">.Add(</span><span style="color: purple">$vmSwitchElementName</span><span style="color: black">)
    }
}

</span><span style="color: green"># Use the first available VM Nic Switch - this assumes 
# I do not create more than on per each environment.
</span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">.Count </span><span style="color: red">-gt </span><span style="color: black">0)
{
    </span><span style="color: purple">$vmVirtualSwitch </span><span style="color: red">= </span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">[0]
}

</span><span style="color: green"># add a legacy network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch </span><span style="color: black">-legacy

</span><span style="color: green"># add a default VMBus (non-legacy) network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch

</span><span style="color: green"># add the hard drive to the VM
</span><span style="color: purple">$parent </span><span style="color: red">= </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmParent.vhd&quot;
</span><span style="color: purple">$vhdPath </span><span style="color: red">= </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmName.vhd&quot;
</span><span style="color: black">Add-VMNewHardDisk –vm </span><span style="color: purple">$vm </span><span style="color: black">-controllerID 0 -lun 0 -vhdpath </span><span style="color: purple">$vhdPath </span><span style="color: black">-parent </span><span style="color: purple">$parent

</span><span style="color: green"># get the VM to see if a disk is attached to it, if it is not, then it failed
</span><span style="color: purple">$disks </span><span style="color: red">= </span><span style="color: black">Get-VMDisk -vm </span><span style="color: purple">$vm
$count </span><span style="color: red">= </span><span style="color: black">1

</span><span style="color: green"># if the disk was not successfully added, try and add it again
</span><span style="color: blue">while </span><span style="color: black">(</span><span style="color: purple">$disks </span><span style="color: red">-eq </span><span style="color: purple">$null </span><span style="color: red">-and </span><span style="color: purple">$count </span><span style="color: red">-le </span><span style="color: black">5)
{
    </span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;RETRY $count - The disk was not properly added. Attempting to retry.&quot;
    
    </span><span style="color: green"># delete the disk that was added
    </span><span style="color: #5f9ea0">DeleteVhd </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmName.vhd&quot;
    
    </span><span style="color: black">Add-VMNewHardDisk –vm </span><span style="color: purple">$vm </span><span style="color: black">-controllerID 0 -lun 0 -vhdpath </span><span style="color: purple">$vhdPath </span><span style="color: black">-parent </span><span style="color: purple">$parent
    
    $disks </span><span style="color: red">= </span><span style="color: black">Get-VMDisk -vm </span><span style="color: purple">$vm
    $count</span><span style="color: red">++
</span><span style="color: black">}

</span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: purple">$disks </span><span style="color: red">-eq </span><span style="color: purple">$null</span><span style="color: black">)
{
    </span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;Operation failed to create this virtual machine. Contact an admin.&quot;
</span><span style="color: black">}
</span><span style="color: blue">else
</span><span style="color: black">{
    </span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;Operation completed successfully. Attempting to start the VM.&quot;
    </span><span style="color: black">Start-VM -vm </span><span style="color: purple">$vm </span><span style="color: black">-wait
}</span></pre>
<a href="http://11011.net/software/vspaste"></a>

<p>I have found that the VM creation is not consistently successful on the first pass, so I have added the while loop. Since adding that, I have not had any issues.</p>

<p>I hope these help. They should be easy to change if you prefer snapshots versus differencing disks. Thanks to James O’Neill for creating this library. It makes administering Hyper-V much easier. It is available via <a title="CodePlex" href="http://www.codeplex.com/" target="_blank">CodePlex</a>, where the latest release, updates, and forum support can be found. </p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Installing Windows 7</title>
		<link>http://elegantcode.com/2009/02/09/installing-windows-7/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=installing-windows-7</link>
		<comments>http://elegantcode.com/2009/02/09/installing-windows-7/#comments</comments>
		<pubDate>Mon, 09 Feb 2009 21:14:36 +0000</pubDate>
		<dc:creator>Alex Mueller</dc:creator>
				<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Operating Systems]]></category>
		<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/02/09/installing-windows-7/</guid>
		<description><![CDATA[The short story is this. If you are accessing Windows 7 from your MSDN subscriptions, save yourself time and frustration by installing the Windows 7 Beta, not the Windows 7 Beta Checked Build. See available downloads here. This past weekend, I decided to upgrade my work laptop from Vista Enterprise to Windows 7 Ultimate Beta. [...]]]></description>
			<content:encoded><![CDATA[<p>The short story is this. If you are accessing Windows 7 from your MSDN subscriptions, save yourself time and frustration by installing the Windows 7 Beta, not the Windows 7 Beta Checked Build. <a href="http://msdn.microsoft.com/en-us/subscriptions/cc137115.aspx" target="_blank">See available downloads here</a>.</p>  <p>This past weekend, I decided to upgrade my work laptop from Vista Enterprise to Windows 7 Ultimate Beta. I was unable to upgrade from Vista Enterprise to 7 Ultimate because that action is not supported. I then tried to upgrade from Enterprise to 7 Enterprise, but I was unable to upgrade from a staged build to a non-staged build. I decided to repave entirely, choosing Windows 7 Ultimate Beta, and I tried to do all of this on a Friday afternoon, two hours before leaving.</p>  <p>I installed Windows 7 Beta Checked Build (x86) - DVD (English), last updated on January 14, 2009,&#160; from my MSDN subscription. I did not install an internal build. Instead, I decided to go with what is publicly available via MSDN. </p>  <p>Why did I go with a <a href="http://msdn.microsoft.com/en-us/library/ms792442.aspx" target="_blank">Checked Build</a>? Because I failed to read the details describing it. What it cost me in time and frustration, I gain in valuable learning experiences. So it was not a total loss. I received a number of buggy issues with the checked build, mainly the inability for Windows Update to properly download all of my necessary updates, including my video drivers and smart card reader, where the latter enables me to remotely access my work domain. </p>  <p>I gave up and decided to download and install the Windows 7 Beta – DVD (English). Everything works great. I was able to get online, download all of my updates, and connect to my work domain. No issues found so far, and no annoying assertion error popups. </p>  <p>My favorite Windows 7 feature so far (non-UI related) is that PowerShell 2.0 is installed by default. PowerShell 2.0 provides more functionality for remoting, among other enhancements.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/02/09/installing-windows-7/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>PowerShell Documentation</title>
		<link>http://elegantcode.com/2008/12/17/powershell-documentation/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-documentation</link>
		<comments>http://elegantcode.com/2008/12/17/powershell-documentation/#comments</comments>
		<pubDate>Wed, 17 Dec 2008 20:36:54 +0000</pubDate>
		<dc:creator>Alex Mueller</dc:creator>
				<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/12/17/powershell-documentation/</guid>
		<description><![CDATA[PowerShell documentation, you are too honest. Get-Help Remove-Item -Full As I was retrieving information on "Remove-Item," this is what I came across. There is more detail beyond what I am showing, but pay attention to what is bolded. NAME&#160;&#160;&#160; Remove-Item SYNOPSIS&#160;&#160;&#160; Deletes the specified items. SYNTAX&#160;&#160;&#160; Remove-Item [-path] &#60;string[]&#62; [-recurse] [-force] [-include &#60;string[]&#62;] [-&#160;&#160;&#160; exclude [...]]]></description>
			<content:encoded><![CDATA[<p>PowerShell documentation, you are too honest. </p> <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:F2210F5F-69EB-4d4c-AFF7-B8A050E9CC72:2ed0ad7a-f3da-498d-a817-1bb0c8b8f8c3" class="wlWriterSmartContent"><pre  style="width:100%;;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #000000;">Get</span><span style="color: #000000;">-</span><span style="color: #000000;">Help Remove</span><span style="color: #000000;">-</span><span style="color: #000000;">Item </span><span style="color: #000000;">-</span><span style="color: #000000;">Full</span></div></pre></div>
<p>As I was retrieving information on "Remove-Item," this is what I came across. There is more detail beyond what I am showing, but pay attention to what is <strong>bolded</strong>. </p>
<blockquote>
<p>NAME<br>&nbsp;&nbsp;&nbsp; Remove-Item 
<p>SYNOPSIS<br>&nbsp;&nbsp;&nbsp; Deletes the specified items. 
<p>SYNTAX<br>&nbsp;&nbsp;&nbsp; Remove-Item [-path] &lt;string[]&gt; [-recurse] [-force] [-include &lt;string[]&gt;] [-<br>&nbsp;&nbsp;&nbsp; exclude &lt;string[]&gt;] [-filter &lt;string&gt;] [-credential &lt;PSCredential&gt;] [-whatI<br>&nbsp;&nbsp;&nbsp; f] [-confirm] [&lt;CommonParameters&gt;] 
<p>&nbsp;&nbsp;&nbsp; Remove-Item [-literalPath] &lt;string[]&gt; [-recurse] [-force] [-include &lt;string<br>&nbsp;&nbsp;&nbsp; []&gt;] [-exclude &lt;string[]&gt;] [-filter &lt;string&gt;] [-credential &lt;PSCredential&gt;]<br>&nbsp;&nbsp;&nbsp; [-whatIf] [-confirm] [&lt;CommonParameters&gt;] 
<p>DETAILED DESCRIPTION<br>&nbsp;&nbsp;&nbsp; The Remove-Item cmdlet deletes one or more items. Because it is supported b<br>&nbsp;&nbsp;&nbsp; y many providers, it can delete many different types of items, including fi<br>&nbsp;&nbsp;&nbsp; les, directories, registry keys, variables, aliases, certificates, and func<br>&nbsp;&nbsp;&nbsp; tions. 
<p>PARAMETERS<br>&nbsp;&nbsp;&nbsp; -path &lt;string[]&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Specifies a path to the items being removed. Wildcards are permitted. T<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; he parameter name ("-Path") is optional. 
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Required?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; true<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Position?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 1<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Default value&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; N/A - The path must be specified<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept pipeline input?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; true (ByValue, ByPropertyName)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept wildcard characters?&nbsp; true 
<p>&nbsp;&nbsp;&nbsp; -recurse &lt;SwitchParameter&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Deletes the items in the specified locations and in all child items of<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; the locations. 
<p><strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; The Recurse parameter in this cmdlet does not work properly. </strong>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Required?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; false<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Position?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; named<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Default value&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; False<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept pipeline input?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; false<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept wildcard characters?&nbsp; false 
<p><strong></strong>&nbsp;</p></blockquote>
<p>"Hmmm... Am I feeling lucky? Ahhh, what the hell, let's do it."</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:F2210F5F-69EB-4d4c-AFF7-B8A050E9CC72:a3ee0edf-63f8-43fc-a4fb-22c6277656f8" class="wlWriterSmartContent"><pre  style="width:100%;;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #000000;">Remove</span><span style="color: #000000;">-</span><span style="color: #000000;">Item </span><span style="color: #800000;">&quot;</span><span style="color: #800000;">C:\</span><span style="color: #800000;">&quot;</span><span style="color: #000000;"> </span><span style="color: #000000;">-</span><span style="color: #000000;">Recurse</span></div></pre></div>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/12/17/powershell-documentation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Automate Daily Tasks with PowerShell</title>
		<link>http://elegantcode.com/2009/02/09/installing-windows-7/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=installing-windows-7</link>
		<comments>http://elegantcode.com/2009/02/09/installing-windows-7/#comments</comments>
		<pubDate>Mon, 09 Feb 2009 21:14:36 +0000</pubDate>
		<dc:creator>Alex Mueller</dc:creator>
				<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Operating Systems]]></category>
		<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/02/09/installing-windows-7/</guid>
		<description><![CDATA[The short story is this. If you are accessing Windows 7 from your MSDN subscriptions, save yourself time and frustration by installing the Windows 7 Beta, not the Windows 7 Beta Checked Build. See available downloads here. This past weekend, I decided to upgrade my work laptop from Vista Enterprise to Windows 7 Ultimate Beta. [...]]]></description>
			<content:encoded><![CDATA[<p>The short story is this. If you are accessing Windows 7 from your MSDN subscriptions, save yourself time and frustration by installing the Windows 7 Beta, not the Windows 7 Beta Checked Build. <a href="http://msdn.microsoft.com/en-us/subscriptions/cc137115.aspx" target="_blank">See available downloads here</a>.</p>  <p>This past weekend, I decided to upgrade my work laptop from Vista Enterprise to Windows 7 Ultimate Beta. I was unable to upgrade from Vista Enterprise to 7 Ultimate because that action is not supported. I then tried to upgrade from Enterprise to 7 Enterprise, but I was unable to upgrade from a staged build to a non-staged build. I decided to repave entirely, choosing Windows 7 Ultimate Beta, and I tried to do all of this on a Friday afternoon, two hours before leaving.</p>  <p>I installed Windows 7 Beta Checked Build (x86) - DVD (English), last updated on January 14, 2009,&#160; from my MSDN subscription. I did not install an internal build. Instead, I decided to go with what is publicly available via MSDN. </p>  <p>Why did I go with a <a href="http://msdn.microsoft.com/en-us/library/ms792442.aspx" target="_blank">Checked Build</a>? Because I failed to read the details describing it. What it cost me in time and frustration, I gain in valuable learning experiences. So it was not a total loss. I received a number of buggy issues with the checked build, mainly the inability for Windows Update to properly download all of my necessary updates, including my video drivers and smart card reader, where the latter enables me to remotely access my work domain. </p>  <p>I gave up and decided to download and install the Windows 7 Beta – DVD (English). Everything works great. I was able to get online, download all of my updates, and connect to my work domain. No issues found so far, and no annoying assertion error popups. </p>  <p>My favorite Windows 7 feature so far (non-UI related) is that PowerShell 2.0 is installed by default. PowerShell 2.0 provides more functionality for remoting, among other enhancements.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/02/09/installing-windows-7/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Elegant Code &#187; PowerShell</title>
	<atom:link href="http://elegantcode.com/category/microsoft/powershell/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Silverlight Profiling PowerShell helper.</title>
		<link>http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=silverlight-profiling-powershell-helper</link>
		<comments>http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/#comments</comments>
		<pubDate>Sat, 15 May 2010 16:47:22 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/</guid>
		<description><![CDATA[I was playing around with some Silverlight profiling the other night to see if I could find any obvious issues with my open source project StatLight and wound up writing a little script in PowerShell I hoped someone might find helpful. But I didn’t know you could profile a Silverlight app. I didn’t until I [...]]]></description>
			<content:encoded><![CDATA[<p>I was playing around with some Silverlight profiling the other night to see if I could find any obvious issues with my open source project <a href="http://statlight.net" target="_blank">StatLight</a> and wound up writing a little script in PowerShell I hoped someone might find helpful.</p>  <h4>But I didn’t know you could profile a Silverlight app.</h4>  <p>I didn’t until I started doing some digging online. Now, the Silverlight profiling story (at least from what I’ve seen/tried) is not near the easy of say <a href="http://www.red-gate.com/products/ants_performance_profiler/index.htm">Redgate ANTS Performance Profiler</a>. However, it’s do-able. (And with this helper script – hopefully a little simpler?)</p>  <h4>How can I profile a Silverlight Application?</h4>  <p>I would recommend you read the following blog, which explains one way of doing it very well.</p>  <p><a title="http://blogs.msdn.com/profiler/archive/2010/04/26/vs2010-silverlight-4-profiling.aspx" href="http://blogs.msdn.com/profiler/archive/2010/04/26/vs2010-silverlight-4-profiling.aspx">http://blogs.msdn.com/profiler/archive/2010/04/26/vs2010-silverlight-4-profiling.aspx</a></p>  <h4>So… what’s this script for?</h4>  <p>If you read the blog above, or have done this before, then you probably noticed that there was quite a series of commands you had to execute before you could wind up with a performance report. </p>  <p>I threw together a quick little PowerShell script in an attempt to automate smooth out the process.</p>  <h4>Hot do I use it?</h4>  <ol>   <li>Download the script &amp; save it somewhere. <a href="http://github.com/staxmanade/Scripts/blob/master/SilverlightProfiler.ps1"><strong>http://github.com/staxmanade/Scripts/blob/master/SilverlightProfiler.ps1</strong></a> </li>    <li>Open the PowerShell console. cd to the directory your xap/assemblies are stored.      <br />(EX: {myProject}\Bin\Debug\ ) </li>    <li>Execute:      <br />{pathToScript}\SilverlightProfiler.ps1 -urlPath &quot;{myProject}\Bin\Debug\TestPage.html&quot; </li>    <li>When your done profiling press enter to signal that your done.      <p></p> Once complete, it will print the location your profiling report was saved. You can then open it with Visual Studio.</li> </ol>  <h5>Couple of disclaimers.</h5>  <ul>   <li>Some paths are hard-coded to my x86 machine. </li>    <li>I had troubles running the built in visual studio .bat files (from powershell) that are supposed to set the environment variables. So I extracted out what vars I could find to make it work. </li>    <li>I’m not a profiling expert – just hacked this together to get it to work for me.</li> </ul>  <p>I hope this is useful, and if you know of a better way, I’m always interested in hearing your feedback.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Powershell: Load assembly without locking file.</title>
		<link>http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-load-assembly-without-locking-file</link>
		<comments>http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/#comments</comments>
		<pubDate>Wed, 23 Dec 2009 05:40:23 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/</guid>
		<description><![CDATA[I have a set of PowerShell build scripts and ran into a case where I needed to load an assembly (to get the assembly’s version) and still (at a later time) work with the assembly file on disk. A typical way to load an assembly within PowerShell is to use the Assembly.LoadFrom(filePath) # Powershell [System.Reflection.Assembly]::LoadFrom($assemblyPath) [...]]]></description>
			<content:encoded><![CDATA[<p>I have a set of PowerShell build scripts and ran into a case where I needed to load an assembly (to get the assembly’s version) and still (at a later time) work with the assembly file on disk.</p>  <p>A typical way to load an assembly within PowerShell is to use the Assembly.LoadFrom(filePath)</p>  <blockquote>   <p># Powershell</p>    <p>[System.Reflection.Assembly]::LoadFrom($assemblyPath)</p> </blockquote>  <p><a href="http://elegantcode.com/wp-content/uploads/2009/12/image9.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://elegantcode.com/wp-content/uploads/2009/12/image_thumb9.png" width="690" height="391" /></a> </p>  <p>Except the problem with this (in my case) was it would <strong>lock the file for the lifespan of the PowerShell console instance</strong>. I didn’t want to have to close and re-open the PowerShell console every time I need to run a build so there had to be a work-around for this.</p>  <p>After searching the web for a solution, I couldn’t find anything that was “easy” and worth the effort to get it to work.</p>  <blockquote>   <p>EX: One solution was to create a new AppDomain, do the necessary work and the close the AppDomain which would release the lock on the file.</p>    <p>I’ve never done this myself, and even thought there is example code out there to get this accomplished, it just seemed over the top for what I was trying to do, and back to my previous criteria it wasn’t “worth the effort to get it to work”</p> </blockquote>  <p>Then I remembered in a previous life I used an overload that took an array of bytes to load the an assembly.</p>  <blockquote>   <p>[System.Reflection.Assembly]::Load($assemblyBytes)</p> </blockquote>  <p>After spiking it in PowerShell with the below test. I was quite happy with the solution, so I thought I’d throw it out there.</p>  <p>Just stream the assembly from disk into a byte array manually, and call assembly load from there.</p>  <p>Here’s my test case which shows that the file is not locked after it was loaded into the PowerShell runtime</p>  <pre>$file = &quot;.\Moq.dll&quot;
$tempFileName = &quot;.\Moq-Renamed.dll&quot;

$fileStream = ([System.IO.FileInfo] (Get-Item $file)).OpenRead();
$assemblyBytes = new-object byte[] $fileStream.Length
$fileStream.Read($assemblyBytes, 0, $fileStream.Length);
$fileStream.Close();

$assemblyLoaded = [System.Reflection.Assembly]::Load($assemblyBytes);

# notice that we can move the file on disk after 
# it's loaded into the powershell runtime
Move-Item $file $tempFileName
Move-Item $tempFileName $file 

# and display the assembly information to show we still have it in memory
echo $assemblyLoaded</pre>

<p>After that test passed, and the main reason I wanted to do this, I wrote the “get-assembly-version” PowerShell function.</p>

<pre><strike>function get-assembly-version() {
    param([string] $file)
    
    # load the assembly bytes quickly - as to not lock the file for too long
    $fileStream = ([System.IO.FileInfo] (Get-Item $file)).OpenRead()
    $assemblyBytes = new-object byte[] $fileStream.Length
    $fileStream.Read($assemblyBytes, 0, $fileStream.Length) | Out-Null #out null this because this function should only return the version &amp; this call was outputting some garbage number
    $fileStream.Close()
    
    # return the version of the assembly
    [System.Reflection.Assembly]::Load($assemblyBytes).GetName().Version;
}

$version = get-assembly-version(&quot;.\Moq.dll&quot;)

echo &quot;Loaded v$($version.Major).$($version.Minor).$($version.Build).$($version.Revision) version of $file&quot;</strike></pre>
Hope this helps someone out there! 

<p></p>

<p>&#160;</p>

<p><strong>UPDATE:</strong></p>

<p><a href="http://achuebrigens.wordpress.com">Martin</a> commented below on a much better solution to the assembly version info problem. Amazing how complicated we can make things if we don’t know the path.</p>

<pre>
function get-assembly-version() {
    param([string] $file)
    
    $version = [System.Reflection.AssemblyName]::GetAssemblyName($file).Version;
    
    #format the version and output it...
    $version
}</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Integration Test Brought to you by Powershell &amp; NUnit &#8211; with a Little Specification Syntax for Flavoring</title>
		<link>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring</link>
		<comments>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/#comments</comments>
		<pubDate>Mon, 26 Oct 2009 05:00:40 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/</guid>
		<description><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about Fluent Specification Extensions in a past blog. Recently I wanted to execute a PowerShell script [...]]]></description>
			<content:encoded><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about <a href="http://staxmanade.blogspot.com/2009/02/fluent-specification-extensions.html">Fluent Specification Extensions</a> in a past blog.

Recently I wanted to execute a PowerShell script to do some automated <a href="http://en.wikipedia.org/wiki/Functional_testing">functional testing</a>. I wanted to execute an application and apply some assertions on the output of the software(basically running a console app, parse the xml output and assert on values in the output).
<blockquote>FYI: I’m very new to PowerShell, so any suggestions on how I implemented the below are welcome…</blockquote>
I’ve seen a couple examples of writing test assertions in PowerShell out there. One example is <a href="http://www.psunit.org/">PSUnit</a>; however, this seemed a little heavy for my needs and not quite the syntactic sugar I was looking for.

Besides the syntax flavor I was desiring, another thing I wanted to do was leverage the power of NUnit.Framework’s assertion capabilities. I like the error messages generated when strings and other objects fail the assertion.
<h5>Examples of end result ShouldLookLike()…</h5>
$true.ShouldBeTrue()
$false.ShouldBeFalse()
"a".ShouldEqual("a")
"a".ShouldNotEqual("b")
<h5><strong>Step 1</strong>: Figure out how to write a C# style <a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx">extension method</a> in PowerShell.</h5>
<blockquote>I found a great blog post describing how to extend any PowerShell object to add extension methods.

<a href="http://bartdesmet.net/blogs/bart/archive/2007/09/06/extension-methods-in-windows-powershell.aspx">Extension Methods in Windows PowerShell</a></blockquote>
In short, to extend types in PowerShell leveraging the <a href="http://msdn.microsoft.com/en-us/library/ms714419(VS.85).aspx">Extended Type System</a>, you need to define them in an xml file and import the method definitions into the PowerShell runtime instance.

Below is PowerShell XML definition for my NUnit Specification Extensions.
<pre class="brush: xml;">&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;Types&gt;
    &lt;Type&gt;
        &lt;Name&gt;System.Object&lt;/Name&gt;
        &lt;Members&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeFalse&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsFalse($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeTrue&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsTrue($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldNotEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreNotEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
        &lt;/Members&gt;
    &lt;/Type&gt;
&lt;/Types&gt;</pre>
<h4></h4>
Take the above XML and save it to a file…
<blockquote>NOTE: the file HAS to be saved with the extension <strong>.ps1xml</strong>

Ex: NunitSpecificationPowerShellExtensions<strong>.ps1xml</strong></blockquote>
<h4></h4>
<h5>Step 2: Load the extended type definition into the PowerShell runtime.</h5>
Once you’ve saved the XML extended types to a file, you need to load it into the PowerShell runtime by executing the command below.
<blockquote>
Update-TypeData -PrependPath NunitSpecificationPowerShellExtensions.ps1xml</blockquote>
Before executing the above statement…Let’s quickly look at a System.String’s members and properties – just to show you what the extension methods look like when applied inside of the runtime.<a href="http://elegantcode.com/wp-content/uploads/2009/10/image3.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb2.png" border="0" alt="image" width="586" height="479" /></a>

After executing the Update-TypeData command you’ll notice there are a number of “ScriptMethod” MemberTypes added to the object.

<a href="http://elegantcode.com/wp-content/uploads/2009/10/image4.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb3.png" border="0" alt="image" width="600" height="580" /></a>

Now if you try to execute one of those newly added extension methods, you may get the following error…

PS C:\&gt; $testVar.<strong>ShouldEqual</strong>("hello world")

Exception calling "ShouldEqual" with "1" argument(s): "<strong>Unable to find type [NUnit.Framework.Assert]: make sure that the

assembly containing this type is loaded.</strong>"

At line:1 char:21

+ $testVar.ShouldEqual &lt;&lt;&lt;&lt; ("hello world")

+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

+ FullyQualifiedErrorId : ScriptMethodRuntimeException

This is because we need to load the NUnit.Framework assembly into the runtime before we can leverage the extension methods.
<blockquote>[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null</blockquote>
Now that the extension methods have been defined and loaded into the runtime, NUnit.Framework is loaded, we can now use the methods on any object that inherits from System.Object (which, as far as I know, is everything in PowerShell).

And now, everything you need in one script (if you have the xml extended type file saved somewhere…)
<pre>#
# Update-TypeData -prependPath C:\Code\NunitSpecificationPowerShellExtensions.ps1xml
#

[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null

$true.ShouldBeTrue()

$false.ShouldBeFalse()

"a".ShouldEqual("a")

"a".ShouldNotEqual("b")</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>PowerShell Management Library for Hyper-V</title>
		<link>http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-management-library-for-hyper-v</link>
		<comments>http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/#comments</comments>
		<pubDate>Wed, 25 Mar 2009 21:46:16 +0000</pubDate>
		<dc:creator>Alex Mueller</dc:creator>
				<category><![CDATA[Hyper-V]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Tools and Utilities]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/</guid>
		<description><![CDATA[I am always looking for tools to allow me to do more by doing less. Administering Hyper-V with PowerShell can be tedious. James O’Neill’s PowerShell Management Library for Hyper-V is a great tool to improve automation of Hyper-V management using PowerShell. As a tester, I am constantly creating new environments, installing our product, taking snapshots, [...]]]></description>
			<content:encoded><![CDATA[<p>I am always looking for tools to allow me to do more by doing less. Administering Hyper-V with PowerShell can be tedious. James O’Neill’s <a href="http://pshyperv.codeplex.com/" target="_blank">PowerShell Management Library for Hyper-V</a> is a great tool to improve automation of Hyper-V management using PowerShell.</p>  <p>As a tester, I am constantly creating new environments, installing our product, taking snapshots, ect. Doing this by hand is a waste of time in my opinion. Doing this with a script makes life easier and frees up my time. </p>  <p>Typically, I prefer to create is to create one VM and to have other VMs inherit from that base image. My second VM (the first child to inherit from the base), I will install daily builds of our product. I will then create a third child, which I use a sandbox. I can easily delete it and recreate as needed without having to install our product over again. I have not consistently found success with using snapshots, so I prefer to use differencing disks. The examples below use differencing disks. </p>  <p>This first code block shows how I am using the PowerShell management library to simply the creation of a base VM. There is nothing magic about it. It’s pretty strait-forward. I create a VM, give it a name, set the CPU count, memory size, network adapters, hard drive, and DVD drive.</p>  <pre class="code"><span style="color: purple">$server </span><span style="color: red">= </span><span style="color: maroon">&quot;my-dev-server&quot;
</span><span style="color: purple">$vmName </span><span style="color: red">= </span><span style="color: maroon">&quot;TestParentVM&quot;
</span><span style="color: purple">$vmVirtualSwitch </span><span style="color: red">= </span><span style="color: maroon">&quot;My Virtual Network&quot;

</span><span style="color: green"># create a new virtual machine
</span><span style="color: purple">$vm </span><span style="color: red">= </span><span style="color: black">New-VM </span><span style="color: purple">$vmName </span><span style="color: black">-server </span><span style="color: purple">$server

</span><span style="color: green"># set cpu count
</span><span style="color: black">Set-VMCPUCount </span><span style="color: purple">$vm </span><span style="color: black">2 -server </span><span style="color: purple">$server

</span><span style="color: green"># set memory size
</span><span style="color: black">Set-VMMemory </span><span style="color: purple">$vm </span><span style="color: black">2 -memory 4GB -server </span><span style="color: purple">$server

</span><span style="color: green"># add a legacy network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch </span><span style="color: black">-legacy

</span><span style="color: green"># add a default VMBus (non-legacy) network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch

</span><span style="color: green"># add the hard drive to the VM
</span><span style="color: black">Add-VMNewHardDisk –vm </span><span style="color: purple">$vm </span><span style="color: black">-controllerID 0 -lun 0 -vhdpath </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmName.vhd&quot; </span><span style="color: black">-size 20GB

</span><span style="color: green"># add the DVD with bootup ISO
</span><span style="color: black">Add-VMDRIVE –vm </span><span style="color: purple">$vm </span><span style="color: black">1 1 -server </span><span style="color: purple">$server </span><span style="color: black">-DVD 

</span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;Operation complete.&quot;</span></pre>
<a href="http://11011.net/software/vspaste"></a>

<p>The next code block will create a differencing disk pointing to the parent created in the previous example. I create the usual, VM, CPU count, ect. What makes this a differencing disk is how the VHD is created by specifying the parent. I do some cleanup in this routine by deleting any previously created VMs or VHDs, and I loop through the creation a failure preventative. </p>

<pre class="code"><span style="color: purple">$server </span><span style="color: red">= </span><span style="color: maroon">&quot;my-dev-server&quot;
</span><span style="color: purple">$vmName </span><span style="color: red">= </span><span style="color: maroon">&quot;TestChildVM&quot;
</span><span style="color: purple">$vmParent </span><span style="color: red">= </span><span style="color: maroon">&quot;TestParentVM&quot;
</span><span style="color: purple">$vmVirtualSwitch </span><span style="color: red">= </span><span style="color: maroon">&quot;My Virtual Network&quot;

</span><span style="color: blue">#region </span><span style="color: black">functions - feel free to move to a separate file

</span><span style="color: blue">Function </span><span style="color: #5f9ea0">DeleteVhd
</span><span style="color: black">{
    </span><span style="color: blue">Param </span><span style="color: black">(</span><span style="color: purple">$pathToVhd</span><span style="color: black">)
    </span><span style="color: green"># delete the disk that was added if it exists
    </span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: #5f9ea0">test-path -path </span><span style="color: purple">$pathToVhd</span><span style="color: black">)
    {
        </span><span style="color: #5f9ea0">Remove-Item -Path </span><span style="color: purple">$pathToVhd </span><span style="color: #5f9ea0">-Force
    </span><span style="color: black">}
}

</span><span style="color: blue">#endregion

</span><span style="color: green"># delete the VHD if it already exists
</span><span style="color: #5f9ea0">DeleteVhd </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmName.vhd&quot;

</span><span style="color: green"># delete the VM if it already exists
</span><span style="color: black">Remove-VM -vm </span><span style="color: purple">$vmName </span><span style="color: black">-server </span><span style="color: purple">$server

</span><span style="color: green"># create a new virtual machine
</span><span style="color: purple">$vm </span><span style="color: red">= </span><span style="color: black">New-VM </span><span style="color: purple">$vmName </span><span style="color: black">-server </span><span style="color: purple">$server

</span><span style="color: green"># get the vm
</span><span style="color: purple">$vm </span><span style="color: red">= </span><span style="color: black">Get-VM </span><span style="color: purple">$vmName

</span><span style="color: green"># set cpu count
</span><span style="color: black">Set-VMCPUCount </span><span style="color: purple">$vm </span><span style="color: black">2 -server </span><span style="color: purple">$server

</span><span style="color: green"># set memory size
</span><span style="color: black">Set-VMMemory </span><span style="color: purple">$vm </span><span style="color: black">2 -memory 4GB -server </span><span style="color: purple">$server

</span><span style="color: green"># get VM Nics available
</span><span style="color: purple">$vmNics </span><span style="color: red">= </span><span style="color: black">Get-VMNic -server </span><span style="color: purple">$server </span><span style="color: black">-vmbus -legacy
</span><span style="color: purple">$vmNicSwitchList </span><span style="color: red">= </span><span style="color: #5f9ea0">New-Object </span><span style="color: maroon">System.Collections.ArrayList

</span><span style="color: green"># get VM Nic Switch available for each VM Nic and add it to our list
</span><span style="color: blue">foreach </span><span style="color: black">(</span><span style="color: purple">$vmNic </span><span style="color: blue">in </span><span style="color: purple">$vmNics</span><span style="color: black">)
{
    </span><span style="color: purple">$vmSwitchElementName </span><span style="color: red">= </span><span style="color: black">(Get-VMNicSwitch </span><span style="color: purple">$vmNic</span><span style="color: black">).ElementName
    </span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">.Contains(</span><span style="color: purple">$vmSwitchElementName</span><span style="color: black">) </span><span style="color: red">-ne </span><span style="color: blue">$true</span><span style="color: black">)
    {
        </span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">.Add(</span><span style="color: purple">$vmSwitchElementName</span><span style="color: black">)
    }
}

</span><span style="color: green"># Use the first available VM Nic Switch - this assumes 
# I do not create more than on per each environment.
</span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">.Count </span><span style="color: red">-gt </span><span style="color: black">0)
{
    </span><span style="color: purple">$vmVirtualSwitch </span><span style="color: red">= </span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">[0]
}

</span><span style="color: green"># add a legacy network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch </span><span style="color: black">-legacy

</span><span style="color: green"># add a default VMBus (non-legacy) network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch

</span><span style="color: green"># add the hard drive to the VM
</span><span style="color: purple">$parent </span><span style="color: red">= </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmParent.vhd&quot;
</span><span style="color: purple">$vhdPath </span><span style="color: red">= </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmName.vhd&quot;
</span><span style="color: black">Add-VMNewHardDisk –vm </span><span style="color: purple">$vm </span><span style="color: black">-controllerID 0 -lun 0 -vhdpath </span><span style="color: purple">$vhdPath </span><span style="color: black">-parent </span><span style="color: purple">$parent

</span><span style="color: green"># get the VM to see if a disk is attached to it, if it is not, then it failed
</span><span style="color: purple">$disks </span><span style="color: red">= </span><span style="color: black">Get-VMDisk -vm </span><span style="color: purple">$vm
$count </span><span style="color: red">= </span><span style="color: black">1

</span><span style="color: green"># if the disk was not successfully added, try and add it again
</span><span style="color: blue">while </span><span style="color: black">(</span><span style="color: purple">$disks </span><span style="color: red">-eq </span><span style="color: purple">$null </span><span style="color: red">-and </span><span style="color: purple">$count </span><span style="color: red">-le </span><span style="color: black">5)
{
    </span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;RETRY $count - The disk was not properly added. Attempting to retry.&quot;
    
    </span><span style="color: green"># delete the disk that was added
    </span><span style="color: #5f9ea0">DeleteVhd </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmName.vhd&quot;
    
    </span><span style="color: black">Add-VMNewHardDisk –vm </span><span style="color: purple">$vm </span><span style="color: black">-controllerID 0 -lun 0 -vhdpath </span><span style="color: purple">$vhdPath </span><span style="color: black">-parent </span><span style="color: purple">$parent
    
    $disks </span><span style="color: red">= </span><span style="color: black">Get-VMDisk -vm </span><span style="color: purple">$vm
    $count</span><span style="color: red">++
</span><span style="color: black">}

</span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: purple">$disks </span><span style="color: red">-eq </span><span style="color: purple">$null</span><span style="color: black">)
{
    </span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;Operation failed to create this virtual machine. Contact an admin.&quot;
</span><span style="color: black">}
</span><span style="color: blue">else
</span><span style="color: black">{
    </span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;Operation completed successfully. Attempting to start the VM.&quot;
    </span><span style="color: black">Start-VM -vm </span><span style="color: purple">$vm </span><span style="color: black">-wait
}</span></pre>
<a href="http://11011.net/software/vspaste"></a>

<p>I have found that the VM creation is not consistently successful on the first pass, so I have added the while loop. Since adding that, I have not had any issues.</p>

<p>I hope these help. They should be easy to change if you prefer snapshots versus differencing disks. Thanks to James O’Neill for creating this library. It makes administering Hyper-V much easier. It is available via <a title="CodePlex" href="http://www.codeplex.com/" target="_blank">CodePlex</a>, where the latest release, updates, and forum support can be found. </p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Installing Windows 7</title>
		<link>http://elegantcode.com/2009/02/09/installing-windows-7/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=installing-windows-7</link>
		<comments>http://elegantcode.com/2009/02/09/installing-windows-7/#comments</comments>
		<pubDate>Mon, 09 Feb 2009 21:14:36 +0000</pubDate>
		<dc:creator>Alex Mueller</dc:creator>
				<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Operating Systems]]></category>
		<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/02/09/installing-windows-7/</guid>
		<description><![CDATA[The short story is this. If you are accessing Windows 7 from your MSDN subscriptions, save yourself time and frustration by installing the Windows 7 Beta, not the Windows 7 Beta Checked Build. See available downloads here. This past weekend, I decided to upgrade my work laptop from Vista Enterprise to Windows 7 Ultimate Beta. [...]]]></description>
			<content:encoded><![CDATA[<p>The short story is this. If you are accessing Windows 7 from your MSDN subscriptions, save yourself time and frustration by installing the Windows 7 Beta, not the Windows 7 Beta Checked Build. <a href="http://msdn.microsoft.com/en-us/subscriptions/cc137115.aspx" target="_blank">See available downloads here</a>.</p>  <p>This past weekend, I decided to upgrade my work laptop from Vista Enterprise to Windows 7 Ultimate Beta. I was unable to upgrade from Vista Enterprise to 7 Ultimate because that action is not supported. I then tried to upgrade from Enterprise to 7 Enterprise, but I was unable to upgrade from a staged build to a non-staged build. I decided to repave entirely, choosing Windows 7 Ultimate Beta, and I tried to do all of this on a Friday afternoon, two hours before leaving.</p>  <p>I installed Windows 7 Beta Checked Build (x86) - DVD (English), last updated on January 14, 2009,&#160; from my MSDN subscription. I did not install an internal build. Instead, I decided to go with what is publicly available via MSDN. </p>  <p>Why did I go with a <a href="http://msdn.microsoft.com/en-us/library/ms792442.aspx" target="_blank">Checked Build</a>? Because I failed to read the details describing it. What it cost me in time and frustration, I gain in valuable learning experiences. So it was not a total loss. I received a number of buggy issues with the checked build, mainly the inability for Windows Update to properly download all of my necessary updates, including my video drivers and smart card reader, where the latter enables me to remotely access my work domain. </p>  <p>I gave up and decided to download and install the Windows 7 Beta – DVD (English). Everything works great. I was able to get online, download all of my updates, and connect to my work domain. No issues found so far, and no annoying assertion error popups. </p>  <p>My favorite Windows 7 feature so far (non-UI related) is that PowerShell 2.0 is installed by default. PowerShell 2.0 provides more functionality for remoting, among other enhancements.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/02/09/installing-windows-7/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>PowerShell Documentation</title>
		<link>http://elegantcode.com/2008/12/17/powershell-documentation/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-documentation</link>
		<comments>http://elegantcode.com/2008/12/17/powershell-documentation/#comments</comments>
		<pubDate>Wed, 17 Dec 2008 20:36:54 +0000</pubDate>
		<dc:creator>Alex Mueller</dc:creator>
				<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/12/17/powershell-documentation/</guid>
		<description><![CDATA[PowerShell documentation, you are too honest. Get-Help Remove-Item -Full As I was retrieving information on "Remove-Item," this is what I came across. There is more detail beyond what I am showing, but pay attention to what is bolded. NAME&#160;&#160;&#160; Remove-Item SYNOPSIS&#160;&#160;&#160; Deletes the specified items. SYNTAX&#160;&#160;&#160; Remove-Item [-path] &#60;string[]&#62; [-recurse] [-force] [-include &#60;string[]&#62;] [-&#160;&#160;&#160; exclude [...]]]></description>
			<content:encoded><![CDATA[<p>PowerShell documentation, you are too honest. </p> <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:F2210F5F-69EB-4d4c-AFF7-B8A050E9CC72:2ed0ad7a-f3da-498d-a817-1bb0c8b8f8c3" class="wlWriterSmartContent"><pre  style="width:100%;;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #000000;">Get</span><span style="color: #000000;">-</span><span style="color: #000000;">Help Remove</span><span style="color: #000000;">-</span><span style="color: #000000;">Item </span><span style="color: #000000;">-</span><span style="color: #000000;">Full</span></div></pre></div>
<p>As I was retrieving information on "Remove-Item," this is what I came across. There is more detail beyond what I am showing, but pay attention to what is <strong>bolded</strong>. </p>
<blockquote>
<p>NAME<br>&nbsp;&nbsp;&nbsp; Remove-Item 
<p>SYNOPSIS<br>&nbsp;&nbsp;&nbsp; Deletes the specified items. 
<p>SYNTAX<br>&nbsp;&nbsp;&nbsp; Remove-Item [-path] &lt;string[]&gt; [-recurse] [-force] [-include &lt;string[]&gt;] [-<br>&nbsp;&nbsp;&nbsp; exclude &lt;string[]&gt;] [-filter &lt;string&gt;] [-credential &lt;PSCredential&gt;] [-whatI<br>&nbsp;&nbsp;&nbsp; f] [-confirm] [&lt;CommonParameters&gt;] 
<p>&nbsp;&nbsp;&nbsp; Remove-Item [-literalPath] &lt;string[]&gt; [-recurse] [-force] [-include &lt;string<br>&nbsp;&nbsp;&nbsp; []&gt;] [-exclude &lt;string[]&gt;] [-filter &lt;string&gt;] [-credential &lt;PSCredential&gt;]<br>&nbsp;&nbsp;&nbsp; [-whatIf] [-confirm] [&lt;CommonParameters&gt;] 
<p>DETAILED DESCRIPTION<br>&nbsp;&nbsp;&nbsp; The Remove-Item cmdlet deletes one or more items. Because it is supported b<br>&nbsp;&nbsp;&nbsp; y many providers, it can delete many different types of items, including fi<br>&nbsp;&nbsp;&nbsp; les, directories, registry keys, variables, aliases, certificates, and func<br>&nbsp;&nbsp;&nbsp; tions. 
<p>PARAMETERS<br>&nbsp;&nbsp;&nbsp; -path &lt;string[]&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Specifies a path to the items being removed. Wildcards are permitted. T<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; he parameter name ("-Path") is optional. 
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Required?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; true<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Position?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 1<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Default value&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; N/A - The path must be specified<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept pipeline input?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; true (ByValue, ByPropertyName)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept wildcard characters?&nbsp; true 
<p>&nbsp;&nbsp;&nbsp; -recurse &lt;SwitchParameter&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Deletes the items in the specified locations and in all child items of<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; the locations. 
<p><strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; The Recurse parameter in this cmdlet does not work properly. </strong>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Required?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; false<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Position?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; named<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Default value&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; False<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept pipeline input?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; false<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept wildcard characters?&nbsp; false 
<p><strong></strong>&nbsp;</p></blockquote>
<p>"Hmmm... Am I feeling lucky? Ahhh, what the hell, let's do it."</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:F2210F5F-69EB-4d4c-AFF7-B8A050E9CC72:a3ee0edf-63f8-43fc-a4fb-22c6277656f8" class="wlWriterSmartContent"><pre  style="width:100%;;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #000000;">Remove</span><span style="color: #000000;">-</span><span style="color: #000000;">Item </span><span style="color: #800000;">&quot;</span><span style="color: #800000;">C:\</span><span style="color: #800000;">&quot;</span><span style="color: #000000;"> </span><span style="color: #000000;">-</span><span style="color: #000000;">Recurse</span></div></pre></div>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/12/17/powershell-documentation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Automate Daily Tasks with PowerShell</title>
		<link>http://elegantcode.com/2008/12/17/powershell-documentation/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-documentation</link>
		<comments>http://elegantcode.com/2008/12/17/powershell-documentation/#comments</comments>
		<pubDate>Wed, 17 Dec 2008 20:36:54 +0000</pubDate>
		<dc:creator>Alex Mueller</dc:creator>
				<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/12/17/powershell-documentation/</guid>
		<description><![CDATA[PowerShell documentation, you are too honest. Get-Help Remove-Item -Full As I was retrieving information on "Remove-Item," this is what I came across. There is more detail beyond what I am showing, but pay attention to what is bolded. NAME&#160;&#160;&#160; Remove-Item SYNOPSIS&#160;&#160;&#160; Deletes the specified items. SYNTAX&#160;&#160;&#160; Remove-Item [-path] &#60;string[]&#62; [-recurse] [-force] [-include &#60;string[]&#62;] [-&#160;&#160;&#160; exclude [...]]]></description>
			<content:encoded><![CDATA[<p>PowerShell documentation, you are too honest. </p> <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:F2210F5F-69EB-4d4c-AFF7-B8A050E9CC72:2ed0ad7a-f3da-498d-a817-1bb0c8b8f8c3" class="wlWriterSmartContent"><pre  style="width:100%;;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #000000;">Get</span><span style="color: #000000;">-</span><span style="color: #000000;">Help Remove</span><span style="color: #000000;">-</span><span style="color: #000000;">Item </span><span style="color: #000000;">-</span><span style="color: #000000;">Full</span></div></pre></div>
<p>As I was retrieving information on "Remove-Item," this is what I came across. There is more detail beyond what I am showing, but pay attention to what is <strong>bolded</strong>. </p>
<blockquote>
<p>NAME<br>&nbsp;&nbsp;&nbsp; Remove-Item 
<p>SYNOPSIS<br>&nbsp;&nbsp;&nbsp; Deletes the specified items. 
<p>SYNTAX<br>&nbsp;&nbsp;&nbsp; Remove-Item [-path] &lt;string[]&gt; [-recurse] [-force] [-include &lt;string[]&gt;] [-<br>&nbsp;&nbsp;&nbsp; exclude &lt;string[]&gt;] [-filter &lt;string&gt;] [-credential &lt;PSCredential&gt;] [-whatI<br>&nbsp;&nbsp;&nbsp; f] [-confirm] [&lt;CommonParameters&gt;] 
<p>&nbsp;&nbsp;&nbsp; Remove-Item [-literalPath] &lt;string[]&gt; [-recurse] [-force] [-include &lt;string<br>&nbsp;&nbsp;&nbsp; []&gt;] [-exclude &lt;string[]&gt;] [-filter &lt;string&gt;] [-credential &lt;PSCredential&gt;]<br>&nbsp;&nbsp;&nbsp; [-whatIf] [-confirm] [&lt;CommonParameters&gt;] 
<p>DETAILED DESCRIPTION<br>&nbsp;&nbsp;&nbsp; The Remove-Item cmdlet deletes one or more items. Because it is supported b<br>&nbsp;&nbsp;&nbsp; y many providers, it can delete many different types of items, including fi<br>&nbsp;&nbsp;&nbsp; les, directories, registry keys, variables, aliases, certificates, and func<br>&nbsp;&nbsp;&nbsp; tions. 
<p>PARAMETERS<br>&nbsp;&nbsp;&nbsp; -path &lt;string[]&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Specifies a path to the items being removed. Wildcards are permitted. T<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; he parameter name ("-Path") is optional. 
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Required?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; true<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Position?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 1<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Default value&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; N/A - The path must be specified<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept pipeline input?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; true (ByValue, ByPropertyName)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept wildcard characters?&nbsp; true 
<p>&nbsp;&nbsp;&nbsp; -recurse &lt;SwitchParameter&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Deletes the items in the specified locations and in all child items of<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; the locations. 
<p><strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; The Recurse parameter in this cmdlet does not work properly. </strong>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Required?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; false<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Position?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; named<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Default value&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; False<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept pipeline input?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; false<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept wildcard characters?&nbsp; false 
<p><strong></strong>&nbsp;</p></blockquote>
<p>"Hmmm... Am I feeling lucky? Ahhh, what the hell, let's do it."</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:F2210F5F-69EB-4d4c-AFF7-B8A050E9CC72:a3ee0edf-63f8-43fc-a4fb-22c6277656f8" class="wlWriterSmartContent"><pre  style="width:100%;;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #000000;">Remove</span><span style="color: #000000;">-</span><span style="color: #000000;">Item </span><span style="color: #800000;">&quot;</span><span style="color: #800000;">C:\</span><span style="color: #800000;">&quot;</span><span style="color: #000000;"> </span><span style="color: #000000;">-</span><span style="color: #000000;">Recurse</span></div></pre></div>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/12/17/powershell-documentation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Elegant Code &#187; PowerShell</title>
	<atom:link href="http://elegantcode.com/category/microsoft/powershell/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Silverlight Profiling PowerShell helper.</title>
		<link>http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=silverlight-profiling-powershell-helper</link>
		<comments>http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/#comments</comments>
		<pubDate>Sat, 15 May 2010 16:47:22 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/</guid>
		<description><![CDATA[I was playing around with some Silverlight profiling the other night to see if I could find any obvious issues with my open source project StatLight and wound up writing a little script in PowerShell I hoped someone might find helpful. But I didn’t know you could profile a Silverlight app. I didn’t until I [...]]]></description>
			<content:encoded><![CDATA[<p>I was playing around with some Silverlight profiling the other night to see if I could find any obvious issues with my open source project <a href="http://statlight.net" target="_blank">StatLight</a> and wound up writing a little script in PowerShell I hoped someone might find helpful.</p>  <h4>But I didn’t know you could profile a Silverlight app.</h4>  <p>I didn’t until I started doing some digging online. Now, the Silverlight profiling story (at least from what I’ve seen/tried) is not near the easy of say <a href="http://www.red-gate.com/products/ants_performance_profiler/index.htm">Redgate ANTS Performance Profiler</a>. However, it’s do-able. (And with this helper script – hopefully a little simpler?)</p>  <h4>How can I profile a Silverlight Application?</h4>  <p>I would recommend you read the following blog, which explains one way of doing it very well.</p>  <p><a title="http://blogs.msdn.com/profiler/archive/2010/04/26/vs2010-silverlight-4-profiling.aspx" href="http://blogs.msdn.com/profiler/archive/2010/04/26/vs2010-silverlight-4-profiling.aspx">http://blogs.msdn.com/profiler/archive/2010/04/26/vs2010-silverlight-4-profiling.aspx</a></p>  <h4>So… what’s this script for?</h4>  <p>If you read the blog above, or have done this before, then you probably noticed that there was quite a series of commands you had to execute before you could wind up with a performance report. </p>  <p>I threw together a quick little PowerShell script in an attempt to automate smooth out the process.</p>  <h4>Hot do I use it?</h4>  <ol>   <li>Download the script &amp; save it somewhere. <a href="http://github.com/staxmanade/Scripts/blob/master/SilverlightProfiler.ps1"><strong>http://github.com/staxmanade/Scripts/blob/master/SilverlightProfiler.ps1</strong></a> </li>    <li>Open the PowerShell console. cd to the directory your xap/assemblies are stored.      <br />(EX: {myProject}\Bin\Debug\ ) </li>    <li>Execute:      <br />{pathToScript}\SilverlightProfiler.ps1 -urlPath &quot;{myProject}\Bin\Debug\TestPage.html&quot; </li>    <li>When your done profiling press enter to signal that your done.      <p></p> Once complete, it will print the location your profiling report was saved. You can then open it with Visual Studio.</li> </ol>  <h5>Couple of disclaimers.</h5>  <ul>   <li>Some paths are hard-coded to my x86 machine. </li>    <li>I had troubles running the built in visual studio .bat files (from powershell) that are supposed to set the environment variables. So I extracted out what vars I could find to make it work. </li>    <li>I’m not a profiling expert – just hacked this together to get it to work for me.</li> </ul>  <p>I hope this is useful, and if you know of a better way, I’m always interested in hearing your feedback.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/05/15/silverlight-profiling-powershell-helper/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Powershell: Load assembly without locking file.</title>
		<link>http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-load-assembly-without-locking-file</link>
		<comments>http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/#comments</comments>
		<pubDate>Wed, 23 Dec 2009 05:40:23 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/</guid>
		<description><![CDATA[I have a set of PowerShell build scripts and ran into a case where I needed to load an assembly (to get the assembly’s version) and still (at a later time) work with the assembly file on disk. A typical way to load an assembly within PowerShell is to use the Assembly.LoadFrom(filePath) # Powershell [System.Reflection.Assembly]::LoadFrom($assemblyPath) [...]]]></description>
			<content:encoded><![CDATA[<p>I have a set of PowerShell build scripts and ran into a case where I needed to load an assembly (to get the assembly’s version) and still (at a later time) work with the assembly file on disk.</p>  <p>A typical way to load an assembly within PowerShell is to use the Assembly.LoadFrom(filePath)</p>  <blockquote>   <p># Powershell</p>    <p>[System.Reflection.Assembly]::LoadFrom($assemblyPath)</p> </blockquote>  <p><a href="http://elegantcode.com/wp-content/uploads/2009/12/image9.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://elegantcode.com/wp-content/uploads/2009/12/image_thumb9.png" width="690" height="391" /></a> </p>  <p>Except the problem with this (in my case) was it would <strong>lock the file for the lifespan of the PowerShell console instance</strong>. I didn’t want to have to close and re-open the PowerShell console every time I need to run a build so there had to be a work-around for this.</p>  <p>After searching the web for a solution, I couldn’t find anything that was “easy” and worth the effort to get it to work.</p>  <blockquote>   <p>EX: One solution was to create a new AppDomain, do the necessary work and the close the AppDomain which would release the lock on the file.</p>    <p>I’ve never done this myself, and even thought there is example code out there to get this accomplished, it just seemed over the top for what I was trying to do, and back to my previous criteria it wasn’t “worth the effort to get it to work”</p> </blockquote>  <p>Then I remembered in a previous life I used an overload that took an array of bytes to load the an assembly.</p>  <blockquote>   <p>[System.Reflection.Assembly]::Load($assemblyBytes)</p> </blockquote>  <p>After spiking it in PowerShell with the below test. I was quite happy with the solution, so I thought I’d throw it out there.</p>  <p>Just stream the assembly from disk into a byte array manually, and call assembly load from there.</p>  <p>Here’s my test case which shows that the file is not locked after it was loaded into the PowerShell runtime</p>  <pre>$file = &quot;.\Moq.dll&quot;
$tempFileName = &quot;.\Moq-Renamed.dll&quot;

$fileStream = ([System.IO.FileInfo] (Get-Item $file)).OpenRead();
$assemblyBytes = new-object byte[] $fileStream.Length
$fileStream.Read($assemblyBytes, 0, $fileStream.Length);
$fileStream.Close();

$assemblyLoaded = [System.Reflection.Assembly]::Load($assemblyBytes);

# notice that we can move the file on disk after 
# it's loaded into the powershell runtime
Move-Item $file $tempFileName
Move-Item $tempFileName $file 

# and display the assembly information to show we still have it in memory
echo $assemblyLoaded</pre>

<p>After that test passed, and the main reason I wanted to do this, I wrote the “get-assembly-version” PowerShell function.</p>

<pre><strike>function get-assembly-version() {
    param([string] $file)
    
    # load the assembly bytes quickly - as to not lock the file for too long
    $fileStream = ([System.IO.FileInfo] (Get-Item $file)).OpenRead()
    $assemblyBytes = new-object byte[] $fileStream.Length
    $fileStream.Read($assemblyBytes, 0, $fileStream.Length) | Out-Null #out null this because this function should only return the version &amp; this call was outputting some garbage number
    $fileStream.Close()
    
    # return the version of the assembly
    [System.Reflection.Assembly]::Load($assemblyBytes).GetName().Version;
}

$version = get-assembly-version(&quot;.\Moq.dll&quot;)

echo &quot;Loaded v$($version.Major).$($version.Minor).$($version.Build).$($version.Revision) version of $file&quot;</strike></pre>
Hope this helps someone out there! 

<p></p>

<p>&#160;</p>

<p><strong>UPDATE:</strong></p>

<p><a href="http://achuebrigens.wordpress.com">Martin</a> commented below on a much better solution to the assembly version info problem. Amazing how complicated we can make things if we don’t know the path.</p>

<pre>
function get-assembly-version() {
    param([string] $file)
    
    $version = [System.Reflection.AssemblyName]::GetAssemblyName($file).Version;
    
    #format the version and output it...
    $version
}</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/22/powershell-load-assembly-without-locking-file/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Integration Test Brought to you by Powershell &amp; NUnit &#8211; with a Little Specification Syntax for Flavoring</title>
		<link>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring</link>
		<comments>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/#comments</comments>
		<pubDate>Mon, 26 Oct 2009 05:00:40 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/</guid>
		<description><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about Fluent Specification Extensions in a past blog. Recently I wanted to execute a PowerShell script [...]]]></description>
			<content:encoded><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about <a href="http://staxmanade.blogspot.com/2009/02/fluent-specification-extensions.html">Fluent Specification Extensions</a> in a past blog.

Recently I wanted to execute a PowerShell script to do some automated <a href="http://en.wikipedia.org/wiki/Functional_testing">functional testing</a>. I wanted to execute an application and apply some assertions on the output of the software(basically running a console app, parse the xml output and assert on values in the output).
<blockquote>FYI: I’m very new to PowerShell, so any suggestions on how I implemented the below are welcome…</blockquote>
I’ve seen a couple examples of writing test assertions in PowerShell out there. One example is <a href="http://www.psunit.org/">PSUnit</a>; however, this seemed a little heavy for my needs and not quite the syntactic sugar I was looking for.

Besides the syntax flavor I was desiring, another thing I wanted to do was leverage the power of NUnit.Framework’s assertion capabilities. I like the error messages generated when strings and other objects fail the assertion.
<h5>Examples of end result ShouldLookLike()…</h5>
$true.ShouldBeTrue()
$false.ShouldBeFalse()
"a".ShouldEqual("a")
"a".ShouldNotEqual("b")
<h5><strong>Step 1</strong>: Figure out how to write a C# style <a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx">extension method</a> in PowerShell.</h5>
<blockquote>I found a great blog post describing how to extend any PowerShell object to add extension methods.

<a href="http://bartdesmet.net/blogs/bart/archive/2007/09/06/extension-methods-in-windows-powershell.aspx">Extension Methods in Windows PowerShell</a></blockquote>
In short, to extend types in PowerShell leveraging the <a href="http://msdn.microsoft.com/en-us/library/ms714419(VS.85).aspx">Extended Type System</a>, you need to define them in an xml file and import the method definitions into the PowerShell runtime instance.

Below is PowerShell XML definition for my NUnit Specification Extensions.
<pre class="brush: xml;">&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;Types&gt;
    &lt;Type&gt;
        &lt;Name&gt;System.Object&lt;/Name&gt;
        &lt;Members&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeFalse&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsFalse($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeTrue&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsTrue($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldNotEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreNotEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
        &lt;/Members&gt;
    &lt;/Type&gt;
&lt;/Types&gt;</pre>
<h4></h4>
Take the above XML and save it to a file…
<blockquote>NOTE: the file HAS to be saved with the extension <strong>.ps1xml</strong>

Ex: NunitSpecificationPowerShellExtensions<strong>.ps1xml</strong></blockquote>
<h4></h4>
<h5>Step 2: Load the extended type definition into the PowerShell runtime.</h5>
Once you’ve saved the XML extended types to a file, you need to load it into the PowerShell runtime by executing the command below.
<blockquote>
Update-TypeData -PrependPath NunitSpecificationPowerShellExtensions.ps1xml</blockquote>
Before executing the above statement…Let’s quickly look at a System.String’s members and properties – just to show you what the extension methods look like when applied inside of the runtime.<a href="http://elegantcode.com/wp-content/uploads/2009/10/image3.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb2.png" border="0" alt="image" width="586" height="479" /></a>

After executing the Update-TypeData command you’ll notice there are a number of “ScriptMethod” MemberTypes added to the object.

<a href="http://elegantcode.com/wp-content/uploads/2009/10/image4.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb3.png" border="0" alt="image" width="600" height="580" /></a>

Now if you try to execute one of those newly added extension methods, you may get the following error…

PS C:\&gt; $testVar.<strong>ShouldEqual</strong>("hello world")

Exception calling "ShouldEqual" with "1" argument(s): "<strong>Unable to find type [NUnit.Framework.Assert]: make sure that the

assembly containing this type is loaded.</strong>"

At line:1 char:21

+ $testVar.ShouldEqual &lt;&lt;&lt;&lt; ("hello world")

+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

+ FullyQualifiedErrorId : ScriptMethodRuntimeException

This is because we need to load the NUnit.Framework assembly into the runtime before we can leverage the extension methods.
<blockquote>[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null</blockquote>
Now that the extension methods have been defined and loaded into the runtime, NUnit.Framework is loaded, we can now use the methods on any object that inherits from System.Object (which, as far as I know, is everything in PowerShell).

And now, everything you need in one script (if you have the xml extended type file saved somewhere…)
<pre>#
# Update-TypeData -prependPath C:\Code\NunitSpecificationPowerShellExtensions.ps1xml
#

[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null

$true.ShouldBeTrue()

$false.ShouldBeFalse()

"a".ShouldEqual("a")

"a".ShouldNotEqual("b")</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>PowerShell Management Library for Hyper-V</title>
		<link>http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-management-library-for-hyper-v</link>
		<comments>http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/#comments</comments>
		<pubDate>Wed, 25 Mar 2009 21:46:16 +0000</pubDate>
		<dc:creator>Alex Mueller</dc:creator>
				<category><![CDATA[Hyper-V]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Tools and Utilities]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/</guid>
		<description><![CDATA[I am always looking for tools to allow me to do more by doing less. Administering Hyper-V with PowerShell can be tedious. James O’Neill’s PowerShell Management Library for Hyper-V is a great tool to improve automation of Hyper-V management using PowerShell. As a tester, I am constantly creating new environments, installing our product, taking snapshots, [...]]]></description>
			<content:encoded><![CDATA[<p>I am always looking for tools to allow me to do more by doing less. Administering Hyper-V with PowerShell can be tedious. James O’Neill’s <a href="http://pshyperv.codeplex.com/" target="_blank">PowerShell Management Library for Hyper-V</a> is a great tool to improve automation of Hyper-V management using PowerShell.</p>  <p>As a tester, I am constantly creating new environments, installing our product, taking snapshots, ect. Doing this by hand is a waste of time in my opinion. Doing this with a script makes life easier and frees up my time. </p>  <p>Typically, I prefer to create is to create one VM and to have other VMs inherit from that base image. My second VM (the first child to inherit from the base), I will install daily builds of our product. I will then create a third child, which I use a sandbox. I can easily delete it and recreate as needed without having to install our product over again. I have not consistently found success with using snapshots, so I prefer to use differencing disks. The examples below use differencing disks. </p>  <p>This first code block shows how I am using the PowerShell management library to simply the creation of a base VM. There is nothing magic about it. It’s pretty strait-forward. I create a VM, give it a name, set the CPU count, memory size, network adapters, hard drive, and DVD drive.</p>  <pre class="code"><span style="color: purple">$server </span><span style="color: red">= </span><span style="color: maroon">&quot;my-dev-server&quot;
</span><span style="color: purple">$vmName </span><span style="color: red">= </span><span style="color: maroon">&quot;TestParentVM&quot;
</span><span style="color: purple">$vmVirtualSwitch </span><span style="color: red">= </span><span style="color: maroon">&quot;My Virtual Network&quot;

</span><span style="color: green"># create a new virtual machine
</span><span style="color: purple">$vm </span><span style="color: red">= </span><span style="color: black">New-VM </span><span style="color: purple">$vmName </span><span style="color: black">-server </span><span style="color: purple">$server

</span><span style="color: green"># set cpu count
</span><span style="color: black">Set-VMCPUCount </span><span style="color: purple">$vm </span><span style="color: black">2 -server </span><span style="color: purple">$server

</span><span style="color: green"># set memory size
</span><span style="color: black">Set-VMMemory </span><span style="color: purple">$vm </span><span style="color: black">2 -memory 4GB -server </span><span style="color: purple">$server

</span><span style="color: green"># add a legacy network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch </span><span style="color: black">-legacy

</span><span style="color: green"># add a default VMBus (non-legacy) network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch

</span><span style="color: green"># add the hard drive to the VM
</span><span style="color: black">Add-VMNewHardDisk –vm </span><span style="color: purple">$vm </span><span style="color: black">-controllerID 0 -lun 0 -vhdpath </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmName.vhd&quot; </span><span style="color: black">-size 20GB

</span><span style="color: green"># add the DVD with bootup ISO
</span><span style="color: black">Add-VMDRIVE –vm </span><span style="color: purple">$vm </span><span style="color: black">1 1 -server </span><span style="color: purple">$server </span><span style="color: black">-DVD 

</span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;Operation complete.&quot;</span></pre>
<a href="http://11011.net/software/vspaste"></a>

<p>The next code block will create a differencing disk pointing to the parent created in the previous example. I create the usual, VM, CPU count, ect. What makes this a differencing disk is how the VHD is created by specifying the parent. I do some cleanup in this routine by deleting any previously created VMs or VHDs, and I loop through the creation a failure preventative. </p>

<pre class="code"><span style="color: purple">$server </span><span style="color: red">= </span><span style="color: maroon">&quot;my-dev-server&quot;
</span><span style="color: purple">$vmName </span><span style="color: red">= </span><span style="color: maroon">&quot;TestChildVM&quot;
</span><span style="color: purple">$vmParent </span><span style="color: red">= </span><span style="color: maroon">&quot;TestParentVM&quot;
</span><span style="color: purple">$vmVirtualSwitch </span><span style="color: red">= </span><span style="color: maroon">&quot;My Virtual Network&quot;

</span><span style="color: blue">#region </span><span style="color: black">functions - feel free to move to a separate file

</span><span style="color: blue">Function </span><span style="color: #5f9ea0">DeleteVhd
</span><span style="color: black">{
    </span><span style="color: blue">Param </span><span style="color: black">(</span><span style="color: purple">$pathToVhd</span><span style="color: black">)
    </span><span style="color: green"># delete the disk that was added if it exists
    </span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: #5f9ea0">test-path -path </span><span style="color: purple">$pathToVhd</span><span style="color: black">)
    {
        </span><span style="color: #5f9ea0">Remove-Item -Path </span><span style="color: purple">$pathToVhd </span><span style="color: #5f9ea0">-Force
    </span><span style="color: black">}
}

</span><span style="color: blue">#endregion

</span><span style="color: green"># delete the VHD if it already exists
</span><span style="color: #5f9ea0">DeleteVhd </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmName.vhd&quot;

</span><span style="color: green"># delete the VM if it already exists
</span><span style="color: black">Remove-VM -vm </span><span style="color: purple">$vmName </span><span style="color: black">-server </span><span style="color: purple">$server

</span><span style="color: green"># create a new virtual machine
</span><span style="color: purple">$vm </span><span style="color: red">= </span><span style="color: black">New-VM </span><span style="color: purple">$vmName </span><span style="color: black">-server </span><span style="color: purple">$server

</span><span style="color: green"># get the vm
</span><span style="color: purple">$vm </span><span style="color: red">= </span><span style="color: black">Get-VM </span><span style="color: purple">$vmName

</span><span style="color: green"># set cpu count
</span><span style="color: black">Set-VMCPUCount </span><span style="color: purple">$vm </span><span style="color: black">2 -server </span><span style="color: purple">$server

</span><span style="color: green"># set memory size
</span><span style="color: black">Set-VMMemory </span><span style="color: purple">$vm </span><span style="color: black">2 -memory 4GB -server </span><span style="color: purple">$server

</span><span style="color: green"># get VM Nics available
</span><span style="color: purple">$vmNics </span><span style="color: red">= </span><span style="color: black">Get-VMNic -server </span><span style="color: purple">$server </span><span style="color: black">-vmbus -legacy
</span><span style="color: purple">$vmNicSwitchList </span><span style="color: red">= </span><span style="color: #5f9ea0">New-Object </span><span style="color: maroon">System.Collections.ArrayList

</span><span style="color: green"># get VM Nic Switch available for each VM Nic and add it to our list
</span><span style="color: blue">foreach </span><span style="color: black">(</span><span style="color: purple">$vmNic </span><span style="color: blue">in </span><span style="color: purple">$vmNics</span><span style="color: black">)
{
    </span><span style="color: purple">$vmSwitchElementName </span><span style="color: red">= </span><span style="color: black">(Get-VMNicSwitch </span><span style="color: purple">$vmNic</span><span style="color: black">).ElementName
    </span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">.Contains(</span><span style="color: purple">$vmSwitchElementName</span><span style="color: black">) </span><span style="color: red">-ne </span><span style="color: blue">$true</span><span style="color: black">)
    {
        </span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">.Add(</span><span style="color: purple">$vmSwitchElementName</span><span style="color: black">)
    }
}

</span><span style="color: green"># Use the first available VM Nic Switch - this assumes 
# I do not create more than on per each environment.
</span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">.Count </span><span style="color: red">-gt </span><span style="color: black">0)
{
    </span><span style="color: purple">$vmVirtualSwitch </span><span style="color: red">= </span><span style="color: purple">$vmNicSwitchList</span><span style="color: black">[0]
}

</span><span style="color: green"># add a legacy network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch </span><span style="color: black">-legacy

</span><span style="color: green"># add a default VMBus (non-legacy) network adapter
</span><span style="color: black">Add-VMNIC -vm </span><span style="color: purple">$vm </span><span style="color: black">-VirtualSwitch </span><span style="color: purple">$vmVirtualSwitch

</span><span style="color: green"># add the hard drive to the VM
</span><span style="color: purple">$parent </span><span style="color: red">= </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmParent.vhd&quot;
</span><span style="color: purple">$vhdPath </span><span style="color: red">= </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmName.vhd&quot;
</span><span style="color: black">Add-VMNewHardDisk –vm </span><span style="color: purple">$vm </span><span style="color: black">-controllerID 0 -lun 0 -vhdpath </span><span style="color: purple">$vhdPath </span><span style="color: black">-parent </span><span style="color: purple">$parent

</span><span style="color: green"># get the VM to see if a disk is attached to it, if it is not, then it failed
</span><span style="color: purple">$disks </span><span style="color: red">= </span><span style="color: black">Get-VMDisk -vm </span><span style="color: purple">$vm
$count </span><span style="color: red">= </span><span style="color: black">1

</span><span style="color: green"># if the disk was not successfully added, try and add it again
</span><span style="color: blue">while </span><span style="color: black">(</span><span style="color: purple">$disks </span><span style="color: red">-eq </span><span style="color: purple">$null </span><span style="color: red">-and </span><span style="color: purple">$count </span><span style="color: red">-le </span><span style="color: black">5)
{
    </span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;RETRY $count - The disk was not properly added. Attempting to retry.&quot;
    
    </span><span style="color: green"># delete the disk that was added
    </span><span style="color: #5f9ea0">DeleteVhd </span><span style="color: maroon">&quot;$(get-VHDdefaultPath)$vmName.vhd&quot;
    
    </span><span style="color: black">Add-VMNewHardDisk –vm </span><span style="color: purple">$vm </span><span style="color: black">-controllerID 0 -lun 0 -vhdpath </span><span style="color: purple">$vhdPath </span><span style="color: black">-parent </span><span style="color: purple">$parent
    
    $disks </span><span style="color: red">= </span><span style="color: black">Get-VMDisk -vm </span><span style="color: purple">$vm
    $count</span><span style="color: red">++
</span><span style="color: black">}

</span><span style="color: blue">if </span><span style="color: black">(</span><span style="color: purple">$disks </span><span style="color: red">-eq </span><span style="color: purple">$null</span><span style="color: black">)
{
    </span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;Operation failed to create this virtual machine. Contact an admin.&quot;
</span><span style="color: black">}
</span><span style="color: blue">else
</span><span style="color: black">{
    </span><span style="color: #5f9ea0">Write-Host </span><span style="color: maroon">&quot;Operation completed successfully. Attempting to start the VM.&quot;
    </span><span style="color: black">Start-VM -vm </span><span style="color: purple">$vm </span><span style="color: black">-wait
}</span></pre>
<a href="http://11011.net/software/vspaste"></a>

<p>I have found that the VM creation is not consistently successful on the first pass, so I have added the while loop. Since adding that, I have not had any issues.</p>

<p>I hope these help. They should be easy to change if you prefer snapshots versus differencing disks. Thanks to James O’Neill for creating this library. It makes administering Hyper-V much easier. It is available via <a title="CodePlex" href="http://www.codeplex.com/" target="_blank">CodePlex</a>, where the latest release, updates, and forum support can be found. </p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/03/25/powershell-management-library-for-hyper-v/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Installing Windows 7</title>
		<link>http://elegantcode.com/2009/02/09/installing-windows-7/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=installing-windows-7</link>
		<comments>http://elegantcode.com/2009/02/09/installing-windows-7/#comments</comments>
		<pubDate>Mon, 09 Feb 2009 21:14:36 +0000</pubDate>
		<dc:creator>Alex Mueller</dc:creator>
				<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Operating Systems]]></category>
		<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/02/09/installing-windows-7/</guid>
		<description><![CDATA[The short story is this. If you are accessing Windows 7 from your MSDN subscriptions, save yourself time and frustration by installing the Windows 7 Beta, not the Windows 7 Beta Checked Build. See available downloads here. This past weekend, I decided to upgrade my work laptop from Vista Enterprise to Windows 7 Ultimate Beta. [...]]]></description>
			<content:encoded><![CDATA[<p>The short story is this. If you are accessing Windows 7 from your MSDN subscriptions, save yourself time and frustration by installing the Windows 7 Beta, not the Windows 7 Beta Checked Build. <a href="http://msdn.microsoft.com/en-us/subscriptions/cc137115.aspx" target="_blank">See available downloads here</a>.</p>  <p>This past weekend, I decided to upgrade my work laptop from Vista Enterprise to Windows 7 Ultimate Beta. I was unable to upgrade from Vista Enterprise to 7 Ultimate because that action is not supported. I then tried to upgrade from Enterprise to 7 Enterprise, but I was unable to upgrade from a staged build to a non-staged build. I decided to repave entirely, choosing Windows 7 Ultimate Beta, and I tried to do all of this on a Friday afternoon, two hours before leaving.</p>  <p>I installed Windows 7 Beta Checked Build (x86) - DVD (English), last updated on January 14, 2009,&#160; from my MSDN subscription. I did not install an internal build. Instead, I decided to go with what is publicly available via MSDN. </p>  <p>Why did I go with a <a href="http://msdn.microsoft.com/en-us/library/ms792442.aspx" target="_blank">Checked Build</a>? Because I failed to read the details describing it. What it cost me in time and frustration, I gain in valuable learning experiences. So it was not a total loss. I received a number of buggy issues with the checked build, mainly the inability for Windows Update to properly download all of my necessary updates, including my video drivers and smart card reader, where the latter enables me to remotely access my work domain. </p>  <p>I gave up and decided to download and install the Windows 7 Beta – DVD (English). Everything works great. I was able to get online, download all of my updates, and connect to my work domain. No issues found so far, and no annoying assertion error popups. </p>  <p>My favorite Windows 7 feature so far (non-UI related) is that PowerShell 2.0 is installed by default. PowerShell 2.0 provides more functionality for remoting, among other enhancements.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/02/09/installing-windows-7/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>PowerShell Documentation</title>
		<link>http://elegantcode.com/2008/12/17/powershell-documentation/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=powershell-documentation</link>
		<comments>http://elegantcode.com/2008/12/17/powershell-documentation/#comments</comments>
		<pubDate>Wed, 17 Dec 2008 20:36:54 +0000</pubDate>
		<dc:creator>Alex Mueller</dc:creator>
				<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/12/17/powershell-documentation/</guid>
		<description><![CDATA[PowerShell documentation, you are too honest. Get-Help Remove-Item -Full As I was retrieving information on "Remove-Item," this is what I came across. There is more detail beyond what I am showing, but pay attention to what is bolded. NAME&#160;&#160;&#160; Remove-Item SYNOPSIS&#160;&#160;&#160; Deletes the specified items. SYNTAX&#160;&#160;&#160; Remove-Item [-path] &#60;string[]&#62; [-recurse] [-force] [-include &#60;string[]&#62;] [-&#160;&#160;&#160; exclude [...]]]></description>
			<content:encoded><![CDATA[<p>PowerShell documentation, you are too honest. </p> <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:F2210F5F-69EB-4d4c-AFF7-B8A050E9CC72:2ed0ad7a-f3da-498d-a817-1bb0c8b8f8c3" class="wlWriterSmartContent"><pre  style="width:100%;;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #000000;">Get</span><span style="color: #000000;">-</span><span style="color: #000000;">Help Remove</span><span style="color: #000000;">-</span><span style="color: #000000;">Item </span><span style="color: #000000;">-</span><span style="color: #000000;">Full</span></div></pre></div>
<p>As I was retrieving information on "Remove-Item," this is what I came across. There is more detail beyond what I am showing, but pay attention to what is <strong>bolded</strong>. </p>
<blockquote>
<p>NAME<br>&nbsp;&nbsp;&nbsp; Remove-Item 
<p>SYNOPSIS<br>&nbsp;&nbsp;&nbsp; Deletes the specified items. 
<p>SYNTAX<br>&nbsp;&nbsp;&nbsp; Remove-Item [-path] &lt;string[]&gt; [-recurse] [-force] [-include &lt;string[]&gt;] [-<br>&nbsp;&nbsp;&nbsp; exclude &lt;string[]&gt;] [-filter &lt;string&gt;] [-credential &lt;PSCredential&gt;] [-whatI<br>&nbsp;&nbsp;&nbsp; f] [-confirm] [&lt;CommonParameters&gt;] 
<p>&nbsp;&nbsp;&nbsp; Remove-Item [-literalPath] &lt;string[]&gt; [-recurse] [-force] [-include &lt;string<br>&nbsp;&nbsp;&nbsp; []&gt;] [-exclude &lt;string[]&gt;] [-filter &lt;string&gt;] [-credential &lt;PSCredential&gt;]<br>&nbsp;&nbsp;&nbsp; [-whatIf] [-confirm] [&lt;CommonParameters&gt;] 
<p>DETAILED DESCRIPTION<br>&nbsp;&nbsp;&nbsp; The Remove-Item cmdlet deletes one or more items. Because it is supported b<br>&nbsp;&nbsp;&nbsp; y many providers, it can delete many different types of items, including fi<br>&nbsp;&nbsp;&nbsp; les, directories, registry keys, variables, aliases, certificates, and func<br>&nbsp;&nbsp;&nbsp; tions. 
<p>PARAMETERS<br>&nbsp;&nbsp;&nbsp; -path &lt;string[]&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Specifies a path to the items being removed. Wildcards are permitted. T<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; he parameter name ("-Path") is optional. 
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Required?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; true<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Position?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 1<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Default value&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; N/A - The path must be specified<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept pipeline input?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; true (ByValue, ByPropertyName)<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept wildcard characters?&nbsp; true 
<p>&nbsp;&nbsp;&nbsp; -recurse &lt;SwitchParameter&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Deletes the items in the specified locations and in all child items of<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; the locations. 
<p><strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; The Recurse parameter in this cmdlet does not work properly. </strong>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Required?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; false<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Position?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; named<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Default value&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; False<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept pipeline input?&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; false<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Accept wildcard characters?&nbsp; false 
<p><strong></strong>&nbsp;</p></blockquote>
<p>"Hmmm... Am I feeling lucky? Ahhh, what the hell, let's do it."</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:F2210F5F-69EB-4d4c-AFF7-B8A050E9CC72:a3ee0edf-63f8-43fc-a4fb-22c6277656f8" class="wlWriterSmartContent"><pre  style="width:100%;;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #000000;">Remove</span><span style="color: #000000;">-</span><span style="color: #000000;">Item </span><span style="color: #800000;">&quot;</span><span style="color: #800000;">C:\</span><span style="color: #800000;">&quot;</span><span style="color: #000000;"> </span><span style="color: #000000;">-</span><span style="color: #000000;">Recurse</span></div></pre></div>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/12/17/powershell-documentation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Automate Daily Tasks with PowerShell</title>
		<link>http://elegantcode.com/2008/12/08/automate-daily-tasks-with-powershell/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=automate-daily-tasks-with-powershell</link>
		<comments>http://elegantcode.com/2008/12/08/automate-daily-tasks-with-powershell/#comments</comments>
		<pubDate>Tue, 09 Dec 2008 04:32:07 +0000</pubDate>
		<dc:creator>Alex Mueller</dc:creator>
				<category><![CDATA[PowerShell]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2008/12/08/automate-daily-tasks-with-powershell/</guid>
		<description><![CDATA[I consider myself to be a strong follower of the DRY principle. I practice it religiously. Lately, I have been applying DRY outside of my IDE, more specifically, with my build environments and daily developer tasks. For example, every night I clean my build environment, sync up the latest code, and rebuild all products within [...]]]></description>
			<content:encoded><![CDATA[<p>I consider myself to be a strong follower of the DRY principle. I practice it religiously. Lately, I have been applying DRY outside of my IDE, more specifically, with my build environments and daily developer tasks. </p> <p>For example, every night I clean my build environment, sync up the latest code, and rebuild all products within my domain. The total time it takes to clean, sync, and build is over two hours, depending on hardware and connection speed. This has been reduced from over four hours. Now before I do all of this, I need to check my environment to ensure I have all the latest tools and versions of those tools, such as Visual Studio, SQL Server, windows updates, service packs, ect. This is just part of our build environment. Typically, we run this check until we receive a positive response, "all is well." </p> <p>Rather than spend my time running these commands, I automate them, and run them around the clock using Task Scheduler, a BAT file, and PowerShell. </p> <p>I create one scheduled task that runs once per hour, indefinitely. My scheduled task runs a BAT file that calls my PowerShell script. Within my PowerShell script, I create a Hashtable of commands to run and at which hour to run them. Each hour as the script is executed, I get the current hour and see if any tasks are available to run. For example, each night, sometime during the 2 AM hour, I start my full build. I realize that running once per hour limits the number of commands I can run, but for now, this imperfect solution meets my needs. </p> <p></p> <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:F2210F5F-69EB-4d4c-AFF7-B8A050E9CC72:a7988140-752b-4ce1-ad06-71236bd6eeab" class="wlWriterSmartContent">Nightly PowerShell Script - <a style="cursor:hand" onClick="javascript:window.clipboardData.setData('Text', document.getElementById('Code74dbce9c46474edb8d66c67510f3ce94').innerText); ">Copy Code</a><pre id="Code74dbce9c46474edb8d66c67510f3ce94" style="width:100%;;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #66758C;"> 1</span> <span style="color: #008000;">#</span><span style="color: #008000;"> Local variables</span><span style="color: #008000;">
</span><span style="color: #66758C;"> 2</span> <span style="color: #008000;"></span><span style="color: #800080;">$productRoot</span><span style="color: #000000;"> </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #800000;">&quot;</span><span style="color: #800000;">c:\Projects\dev</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">  
</span><span style="color: #66758C;"> 3</span> <span style="color: #000000;"></span><span style="color: #800080;">$currentHour</span><span style="color: #000000;"> </span><span style="color: #000000;">=</span><span style="color: #000000;"> (Get</span><span style="color: #000000;">-</span><span style="color: #000000;">Date).Hour
</span><span style="color: #66758C;"> 4</span> <span style="color: #000000;"></span><span style="color: #800080;">$list</span><span style="color: #000000;"> </span><span style="color: #000000;">=</span><span style="color: #000000;"> New</span><span style="color: #000000;">-</span><span style="color: #000000;">Object System.Collections.Hashtable 
</span><span style="color: #66758C;"> 5</span> <span style="color: #000000;">
</span><span style="color: #66758C;"> 6</span> <span style="color: #000000;"></span><span style="color: #008000;">#</span><span style="color: #008000;"> Define tasks to run each hour</span><span style="color: #008000;">
</span><span style="color: #66758C;"> 7</span> <span style="color: #008000;">#</span><span style="color: #008000;">     Hour 0 = 12:00-12:59 AM</span><span style="color: #008000;">
</span><span style="color: #66758C;"> 8</span> <span style="color: #008000;">#</span><span style="color: #008000;">     Hour 1 = 1:00-1:59 AM</span><span style="color: #008000;">
</span><span style="color: #66758C;"> 9</span> <span style="color: #008000;">#</span><span style="color: #008000;">     Hour 20 = 8:00-8:59 PM</span><span style="color: #008000;">
</span><span style="color: #66758C;">10</span> <span style="color: #008000;"></span><span style="color: #800080;">$list</span><span style="color: #000000;">.Add(</span><span style="color: #000000;">20</span><span style="color: #000000;">,</span><span style="color: #800000;">&quot;</span><span style="color: #800000;">environmentCheck dev</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">);
</span><span style="color: #66758C;">11</span> <span style="color: #000000;"></span><span style="color: #800080;">$list</span><span style="color: #000000;">.Add(</span><span style="color: #000000;">21</span><span style="color: #000000;">,</span><span style="color: #800000;">&quot;</span><span style="color: #800000;">environmentCheck test</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">);
</span><span style="color: #66758C;">12</span> <span style="color: #000000;"></span><span style="color: #800080;">$list</span><span style="color: #000000;">.Add(</span><span style="color: #000000;">22</span><span style="color: #000000;">,</span><span style="color: #800000;">&quot;</span><span style="color: #800000;">environmentCheck system</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">);
</span><span style="color: #66758C;">13</span> <span style="color: #000000;"></span><span style="color: #800080;">$list</span><span style="color: #000000;">.Add(</span><span style="color: #000000;">23</span><span style="color: #000000;">,</span><span style="color: #800000;">&quot;</span><span style="color: #800000;">projects clean sync</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">);
</span><span style="color: #66758C;">14</span> <span style="color: #000000;"></span><span style="color: #800080;">$list</span><span style="color: #000000;">.Add(</span><span style="color: #000000;">2</span><span style="color: #000000;">,</span><span style="color: #800000;">&quot;</span><span style="color: #800000;">projects build full</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">); 
</span><span style="color: #66758C;">15</span> <span style="color: #000000;">
</span><span style="color: #66758C;">16</span> <span style="color: #000000;"></span><span style="color: #008000;">#</span><span style="color: #008000;"> if a task is defined for this hour, execute it</span><span style="color: #008000;">
</span><span style="color: #66758C;">17</span> <span style="color: #008000;"></span><span style="color: #0000FF;">if</span><span style="color: #000000;">(</span><span style="color: #800080;">$list</span><span style="color: #000000;">.Contains(</span><span style="color: #800080;">$currentHour</span><span style="color: #000000;">))
</span><span style="color: #66758C;">18</span> <span style="color: #000000;">{
</span><span style="color: #66758C;">19</span> <span style="color: #000000;">    </span><span style="color: #008000;">#</span><span style="color: #008000;"> Get the command to execute for this hour</span><span style="color: #008000;">
</span><span style="color: #66758C;">20</span> <span style="color: #008000;"></span><span style="color: #000000;">    </span><span style="color: #800080;">$buildCommand</span><span style="color: #000000;"> </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #800080;">$list</span><span style="color: #000000;">[</span><span style="color: #800080;">$currentHour</span><span style="color: #000000;">]
</span><span style="color: #66758C;">21</span> <span style="color: #000000;">
</span><span style="color: #66758C;">22</span> <span style="color: #000000;">    </span><span style="color: #008000;">#</span><span style="color: #008000;"> Set the project bat path</span><span style="color: #008000;">
</span><span style="color: #66758C;">23</span> <span style="color: #008000;"></span><span style="color: #000000;">    </span><span style="color: #800080;">$pathToBat</span><span style="color: #000000;"> </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #800080;">$productRoot</span><span style="color: #000000;"> </span><span style="color: #000000;">+</span><span style="color: #000000;"> </span><span style="color: #800000;">&quot;</span><span style="color: #800000;">\bin\project.bat</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">
</span><span style="color: #66758C;">24</span> <span style="color: #000000;">
</span><span style="color: #66758C;">25</span> <span style="color: #000000;">    </span><span style="color: #008000;">#</span><span style="color: #008000;"> Set the cmd.exe's arguments</span><span style="color: #008000;">
</span><span style="color: #66758C;">26</span> <span style="color: #008000;"></span><span style="color: #000000;">    </span><span style="color: #800080;">$arguments</span><span style="color: #000000;"> </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #800000;">&quot;</span><span style="color: #800000;">/C cd /d </span><span style="color: #800000;">&quot;</span><span style="color: #000000;"> </span><span style="color: #000000;">+</span><span style="color: #000000;"> </span><span style="color: #800080;">$productRoot</span><span style="color: #000000;"> </span><span style="color: #000000;">+</span><span style="color: #000000;"> </span><span style="color: #800000;">&quot;</span><span style="color: #800000;"> &amp; </span><span style="color: #800000;">&quot;</span><span style="color: #000000;"> </span><span style="color: #000000;">+</span><span style="color: #000000;"> </span><span style="color: #800080;">$pathToBat</span><span style="color: #000000;"> </span><span style="color: #000000;">+</span><span style="color: #000000;"> </span><span style="color: #800000;">&quot;</span><span style="color: #800000;"> &amp; </span><span style="color: #800000;">&quot;</span><span style="color: #000000;"> </span><span style="color: #000000;">+</span><span style="color: #000000;"> </span><span style="color: #800080;">$buildCommand</span><span style="color: #000000;">
</span><span style="color: #66758C;">27</span> <span style="color: #000000;">    
</span><span style="color: #66758C;">28</span> <span style="color: #000000;">    </span><span style="color: #008000;">#</span><span style="color: #008000;"> Start up the DOS prompt, execute the commands</span><span style="color: #008000;">
</span><span style="color: #66758C;">29</span> <span style="color: #008000;"></span><span style="color: #000000;">    </span><span style="color: #800080;">$process</span><span style="color: #000000;"> </span><span style="color: #000000;">=</span><span style="color: #000000;"> New</span><span style="color: #000000;">-</span><span style="color: #000000;">Object </span><span style="color: #000000;">-</span><span style="color: #000000;">TypeName System.Diagnostics.</span><span style="color: #0000FF;">Process</span><span style="color: #000000;">
</span><span style="color: #66758C;">30</span> <span style="color: #000000;">    </span><span style="color: #800080;">$process</span><span style="color: #000000;">.StartInfo.FileName </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #800000;">&quot;</span><span style="color: #800000;">cmd.exe</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">
</span><span style="color: #66758C;">31</span> <span style="color: #000000;">    </span><span style="color: #800080;">$process</span><span style="color: #000000;">.StartInfo.Arguments </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #800080;">$arguments</span><span style="color: #000000;">
</span><span style="color: #66758C;">32</span> <span style="color: #000000;">    </span><span style="color: #800080;">$process</span><span style="color: #000000;">.StartInfo.UseShellExecute </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #0000FF;">$false</span><span style="color: #000000;">
</span><span style="color: #66758C;">33</span> <span style="color: #000000;">    </span><span style="color: #800080;">$process</span><span style="color: #000000;">.Start()
</span><span style="color: #66758C;">34</span> <span style="color: #000000;">    </span><span style="color: #800080;">$process</span><span style="color: #000000;">.WaitForExit()
</span><span style="color: #66758C;">35</span> <span style="color: #000000;">} </span></div></pre></div>
<p></p>
<p>Every morning, I expect to have fresh builds. My build system will email me with the results. However, adding email capabilities to the above script with PowerShell is doable. The above commands execute on my dev server, but executing them on remote servers is also doable, even with PowerShell 1.0 and something like the following.</p>
<p></p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:F2210F5F-69EB-4d4c-AFF7-B8A050E9CC72:e732d6b0-bd96-4b2a-a419-f867afe918d1" class="wlWriterSmartContent">Execute Command Remotely - <a style="cursor:hand" onClick="javascript:window.clipboardData.setData('Text', document.getElementById('Code2b6dd067262345728f29e8941ad2454a').innerText); ">Copy Code</a><pre id="Code2b6dd067262345728f29e8941ad2454a" style="width:100%;;"><div><!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--><span style="color: #999999;">1</span> <span style="color: #800080;">$toServer</span><span style="color: #000000;"> </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #800000;">&quot;</span><span style="color: #800000;">my-remote-server</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">
</span><span style="color: #999999;">2</span> <span style="color: #000000;">([WMICLASS]</span><span style="color: #800000;">&quot;</span><span style="color: #800000;">\\$toServer\ROOT\CIMV2:win32_process</span><span style="color: #800000;">&quot;</span><span style="color: #000000;">).Create(</span><span style="color: #800080;">$command</span><span style="color: #000000;">)</span></div></pre></div>
<p></p>
<p>If my environment is not current and my builds are not working, I can lose productivity during normal business hours. Using a simple scheduled task and PowerShell helps me administer my server and keeps me from repeating the same tedious steps on a daily basis.</p>
<p>How else does PowerShell help me adhere to DRY? It enables me to administer my Hyper-V machines, configure websites, GAC and un-GAC assemblies, and much more.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2008/12/08/automate-daily-tasks-with-powershell/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

