Using PowerShell with Visual Studio – Part I

There are several interesting ways you can integrate Windows PowerShell and Visual Studio. Why would you want to do this? Consider the following scenario: you are using Visual Studio to create a C# project of some sort (a Windows application, a Web application, a Class Library, etc.) You wish to use some very lightweight PowerShell based test automation to supplement your unit tests and your medium weight C# test harnesses. In some situations you might want some sort of PowerShell – Visual Studio integration rather than using each separately. One neat trick is to create a custom Visual Studio Item Type as a PowerShell test script template so that inside Visual Studio you can right click on your Project name and select Add | New Item from the context menu and have your custom PowerShell template available. The process is quite easy in Visual Studio 2005 and 2008. First, create an empty .zip folder named on your Desktop. Next use notepad to create your custom PowerShell template. For example:
# PowerShell test automation template
write-output "Begin tests"
write-output "End test run"
Save this file as PowerShellScript.ps1 on your Desktop. Now use notepad to create this XML meta file:
<VSTemplate Version="2.0.0" Type="Item"
    <Name>My PowerShell Template</Name>
    <Description>My Custom PowerShell File</Description>
Save as PowerShellScript.vstemplate on your Desktop. You should be able to figure out most of this XML file. Notice the Book.ico icon reference. This entry is optional. I hate creating .ico files so I just used one I found. Now copy files PowerShellScript.ps1 and PowerShellScript.vstemplate (and an icon file if you decide to use one) into the directory on your Desktop. Now copy the entire .zip folder into the language-appropriate Visual Studio user-defined template directory. On my Vista machine this is at C:\Users\myname\Documents\Visual Studio 2008\Templates\ItemTemplates\Visual C#. You can find the exact location on your particular machine from Visual Studio by Tools | Options | Projects and Solutions | General. Now, the next time you create any kind of C# project, you’ll have your PowerShell template available as a New Item entry. Very cool. At this point you can write the PowerShell script within the Visual Studio environment where you get the advantages of general file management and integrated .NET help. Now to execute your tests you’d have to launch an instance of PowerShell, navigate to your script and execute it. In my next blog entry I’ll describe an interesting alternative to this last step of the process.


This entry was posted in Software Test Automation. Bookmark the permalink.