Archives

Archives / 2010 / July
  • Taming the VSX beast from PowerShell

    Using VSX from PowerShell is not always a pleasant experience. Most stuff in VSX is still good old COM the System.__ComObject types are flying around. Everything can be casted to everything (for example EnvDTE to EnvDTE2) if you are in C#, but PowerShell can’t make spaghetti of it.

    Enter Power Console. In Power Console there are some neat tricks available to help you out of VSX trouble. And most of the trouble solving is done in… PowerShell. You just need to know what to do.

    To get out of trouble do the following:

    1. Head over to the Power Console site
    2. Right-click on the Download button, and save the PowerConsole.vsix file to your disk
    3. Rename PowerConsole.vsix to PowerConsole.zip and unzip
    4. Look in the Scripts folder for the file Profile.ps1 which is full of PowerShell/VSX magic

    The PowerShell functions that perform the VSX magic are:

    Extract from Profile.ps1
    1. <#
    2. .SYNOPSIS
    3.    Get an explict interface on an object so that you can invoke the interface members.
    4.    
    5. .DESCRIPTION
    6.    PowerShell object adapter does not provide explict interface members. For COM objects
    7.    it only makes IDispatch members available.
    8.    
    9.    This function helps access interface members on an object through reflection. A new
    10.    object is returned with the interface members as ScriptProperties and ScriptMethods.
    11.    
    12. .EXAMPLE
    13.    $dte2 = Get-Interface $dte ([EnvDTE80.DTE2])
    14. #>
    15. function Get-Interface
    16. {
    17.    Param(
    18.        $Object,
    19.        [type]$InterfaceType
    20.    )
    21.    
    22.    [Microsoft.VisualStudio.PowerConsole.Host.PowerShell.Implementation.PSTypeWrapper]::GetInterface($Object, $InterfaceType)
    23. }
    24.  
    25. <#
    26. .SYNOPSIS
    27.    Get a VS service.
    28.  
    29. .EXAMPLE
    30.    Get-VSService ([Microsoft.VisualStudio.Shell.Interop.SVsShell]) ([Microsoft.VisualStudio.Shell.Interop.IVsShell])
    31. #>
    32. function Get-VSService
    33. {
    34.    Param(
    35.        [type]$ServiceType,
    36.        [type]$InterfaceType
    37.    )
    38.  
    39.    $service = [Microsoft.VisualStudio.Shell.Package]::GetGlobalService($ServiceType)
    40.    if ($service -and $InterfaceType) {
    41.        $service = Get-Interface $service $InterfaceType
    42.    }
    43.  
    44.    $service
    45. }
    46.  
    47. <#
    48. .SYNOPSIS
    49.    Get VS IComponentModel service to access VS MEF hosting.
    50. #>
    51. function Get-VSComponentModel
    52. {
    53.    Get-VSService ([Microsoft.VisualStudio.ComponentModelHost.SComponentModel]) ([Microsoft.VisualStudio.ComponentModelHost.IComponentModel])
    54. }

     

    The same Profile.ps1 file contains a nice example of how to use these functions:

    A lot of other good samples can be found on the Power Console site at the home page.

    Now there are two things you can do with respect to the Power Console specific function GetInterface() on line 22:

    1. Make sure that Power Console is installed and load the assembly Microsoft.VisualStudio.PowerConsole.Host.PowerShell.Implementation.dll
    2. Fire-up reflector and investigate the GetInterface() function to isolate the GetInterface code into your own library that only contains this functionality (I did this, it is a lot of work!)

    For this post we use the first approach, the second approach is left for the reader as an exercise:-)

    To try it out I want to present a maybe bit unusual case: I want to be able to access Visual Studio from a PowerShell script that is executed from the MSBuild script building a project.

    In the .csproj of my project I added the following line:

    <!-- Macaw Software Factory targets -->
    <Import Project="..\..\..\..\tools\DotNet2\MsBuildTargets\Macaw.Mast.Targets" />

    The included targets file loads the PowerShell MSBuild Task (CodePlex) that is used to fire a PowerShell script on AfterBuild. Below a relevant excerpt from this targets file:

    Macaw.Mast.Targets
    1. <Project DefaultTargets="AfterBuild" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    2.     <UsingTask  AssemblyFile="PowershellMSBuildTask.dll" TaskName="Powershell"/>
    3.  
    4.     <Target Name="AfterBuild" DependsOnTargets="$(AfterBuildDependsOn)">
    5.         <!-- expand $(TargetDir) to _TargetDir, otherwise error on including in arguments list below -->
    6.         <CreateProperty Value="$(TargetDir)">
    7.             <Output TaskParameter="Value" PropertyName="_TargetDir" />
    8.         </CreateProperty>
    9.         <Message Text="OnBuildSuccess = $(@(IntermediateAssembly))"/>
    10.         <Powershell Arguments="
    11.                   MastBuildAction=build;
    12.                   MastSolutionName=$(SolutionName);
    13.                   MastSolutionDir=$(SolutionDir);
    14.                   MastProjectName=$(ProjectName);
    15.                   MastConfigurationName=$(ConfigurationName);
    16.                   MastProjectDir=$(ProjectDir);
    17.                   MastTargetDir=$(_TargetDir);
    18.                   MastTargetName=$(TargetName);
    19.                   MastPackageForDeployment=$(MastPackageForDeployment);
    20.                   MastSingleProjectBuildAndPackage=$(MastSingleProjectBuildAndPackage)
    21.                 "
    22.                 VerbosePreference="Continue"
    23.                 Script="&amp; (Join-Path -Path &quot;$(SolutionDir)&quot; -ChildPath &quot;..\..\..\tools\MastDeployDispatcher.ps1&quot;)" />
    24.   </Target>
    25. </Project>

    The MastDeployDispatcher.ps1 script is a Macaw Solutions Factory specific script, but you get the idea. To test in which context the PowerShell script is running I added the following lines op PowerShell code to the executed PowerShell script:

    $process = [System.Diagnostics.Process]::GetCurrentProcess()
    Write-Host "Process name: $($a.ProcessName)"

    Which returns:

    Process name: devenv

    So we know our PowerShell script is running in the context of the Visual Studio process. I wonder if this is still the case if you set the maximum number of parallel projects builds to a value higher than 1 (Tools->Options->Projects and Solutions->Build and Run). I did put the value on 10, tried it, and it still worked, but I don’t know if there were more builds running at the same time.

    My first step was to try one of the examples on the Power Console home page: show “Hello world” using the IVsUIShell.ShowMessageBox() function.

    I added the following code to the PowerShell script:

    PowerShell from MSBuild
    1. [void][reflection.assembly]::LoadFrom("C:\Users\serge\Downloads\PowerConsole\Microsoft.VisualStudio.PowerConsole.Host.PowerShell.Implementation.dll")
    2. [void][reflection.assembly]::LoadWithPartialName("Microsoft.VisualStudio.Shell.Interop")
    3.  
    4. function Get-Interface
    5. {
    6.    Param(
    7.        $Object,
    8.        [type]$InterfaceType
    9.    )
    10.    
    11.    [Microsoft.VisualStudio.PowerConsole.Host.PowerShell.Implementation.PSTypeWrapper]::GetInterface($Object, $InterfaceType)
    12. }
    13.  
    14. function Get-VSService
    15. {
    16.    Param(
    17.        [type]$ServiceType,
    18.        [type]$InterfaceType
    19.    )
    20.  
    21.    $service = [Microsoft.VisualStudio.Shell.Package]::GetGlobalService($ServiceType)
    22.    if ($service -and $InterfaceType) {
    23.        $service = Get-Interface $service $InterfaceType
    24.    }
    25.  
    26.    $service
    27. }
    28.  
    29. $msg = "Hello world!"
    30. $shui = Get-VSService `
    31. ([Microsoft.VisualStudio.Shell.Interop.SVsUIShell]) `
    32. ([Microsoft.VisualStudio.Shell.Interop.IVsUIShell])
    33. [void]$shui.ShowMessageBox(0, [System.Guid]::Empty,"", $msg, "", 0, `
    34.     [Microsoft.VisualStudio.Shell.Interop.OLEMSGBUTTON]::OLEMSGBUTTON_OK,
    35.     [Microsoft.VisualStudio.Shell.Interop.OLEMSGDEFBUTTON]::OLEMSGDEFBUTTON_FIRST, `
    36.     [Microsoft.VisualStudio.Shell.Interop.OLEMSGICON]::OLEMSGICON_INFO, 0)

    When I build the project I get the following:

    image

    So we are in business! It is possible to access the Visual Studio object model from a PowerShell script that is fired from the MSBuild script used to build your project. What you can do with that is up to your imagination. Note that you should differentiate between a build done on your developer box, executed from Visual Studio, and a build executed by for example your build server, or executing from MSBuild directly.

  • Powershell: Finding items in a Visual Studio project

    In the Macaw Solutions Factory we execute a lot of PowerShell code in the context of Visual Studio, meaning that we can access the Visual Studio object model directly from our PowerShell code.

    There is a great add-in for Visual Studio that provides you with a PowerShell console within Visual Studio that also allows you to access the Visual Studio object model to play with VSX (Visual Studio Extensibility). This add-in is called Power Console.

    If you paste the function below in this Power Console, you can find a (selection of) project items in a specified Visual Studio project.

    For example:

    FindProjectItems -SolutionRelativeProjectFile 'Business.ServiceInterfaces\Business.ServiceInterfaces.csproj' -Pattern '*.asmx' | select-object RelativeFileName

    returns:

    RelativeFileName                                                                                                                                ----------------
    Internal\AnotherSoapService.asmx
    SampleSoapService.asmx

    What I do is that I extend the standard Visual Studio ProjectItem objects with two fields: FileName (this is the full path to the item) and RelativeFileName (this is the path to the item relative to the project folder (line 53-55). I return a collection of Visual Studio project items, with these additional fields.

    A great way of testing out this kind of code is by editing it in Visual Studio using the PowerGuiVSX add-in (which uses the unsurpassed PowerGui script editor), and copying over the code into the Power Console.

    Find project items
    1. function FindProjectItems
    2. {
    3.     param
    4.     (
    5.         $SolutionRelativeProjectFile,
    6.         $Pattern = '*'
    7.     )
    8.     
    9.     function FindProjectItemsRecurse
    10.     {
    11.         param
    12.         (
    13.             $AbsolutePath,
    14.             $RelativePath = '',
    15.             $ProjectItem,
    16.             $Pattern
    17.         )
    18.  
    19.         $projItemFolder = '{6BB5F8EF-4483-11D3-8BCF-00C04F8EC28C}' # Visual Studio defined constant
    20.         
    21.         if ($ProjectItem.Kind -eq $projItemFolder)
    22.         {
    23.             if ($ProjectItem.ProjectItems -ne $null)
    24.             {
    25.                 if ($RelativePath -eq '')
    26.                 {
    27.                     $relativeFolderPath = $ProjectItem.Name
    28.                 }
    29.                 else
    30.                 {
    31.                     $relativeFolderPath = Join-Path -Path $RelativePath -ChildPath $ProjectItem.Name
    32.                 }
    33.                 $ProjectItem.ProjectItems | ForEach-Object {
    34.                     FindProjectItemsRecurse -AbsolutePath $AbsolutePath -RelativePath $relativeFolderPath -ProjectItem $_ -Pattern $Pattern
    35.                 }
    36.             }
    37.         }
    38.         else
    39.         {
    40.             if ($ProjectItem.Name -like $pattern)
    41.             {
    42.                 if ($RelativePath -eq '')
    43.                 {
    44.                     $relativeFileName = $ProjectItem.Name
    45.                 }
    46.                 else
    47.                 {
    48.                     if ($RelativePath -eq $null) { Write-Host "Relative Path is NULL" }
    49.                     $relativeFileName = Join-Path -Path $RelativePath -ChildPath $ProjectItem.Name
    50.                 }
    51.                 $fileName = Join-Path -Path $AbsolutePath -ChildPath $relativeFileName;
    52.                 
    53.                 $ProjectItem |
    54.                     Add-Member -MemberType NoteProperty -Name RelativeFileName -Value $relativeFileName -PassThru |
    55.                     Add-Member -MemberType NoteProperty -Name FileName -Value $fileName -PassThru
    56.             }
    57.         }
    58.     }
    59.     
    60.     $proj = $DTE.Solution.Projects.Item($SolutionRelativeProjectFile)
    61.     $projPath = Split-Path -Path $proj.FileName -Parent
    62.     if ($proj -eq $null) { throw "No project '$SolutionRelativeProjectFile' found in current solution" }
    63.     $proj.ProjectItems | ForEach-Object {
    64.         FindProjectItemsRecurse -AbsolutePath $projPath -ProjectItem $_ -Pattern $Pattern
    65.     }
    66. }
  • PowerShell internal functions

    Working with PowerShell for years already, never knew that this would work! Internal functions in PowerShell (they probably have a better name):

    function x
    {
        function y
        {
            "function y"
        }
        y
    }

    PS> x

    function y

    PS> y

    ERROR!

  • Returning an exit code from a PowerShell script

    Returning an exit code from a PowerShell script seems easy… but it isn’t that obvious. In this blog post I will show you an approach that works for PowerShell scripts that can be called from both PowerShell and batch scripts, where the command to be executed can be specified in a string, execute in its own context and always return the correct error code.

    Below is a kind of transcript of the steps that I took to get to an approach that works for me. It is a transcript of the steps I took, for the conclusions just jump to the end.

    In many blog posts you can read about calling a PowerShell script that you call from a batch script, and how to return an error code. This comes down to the following:

    c:\temp\exit.ps1:

    Write-Host "Exiting with code 12345"
    exit 12345

    c:\temp\testexit.cmd:

    @PowerShell -NonInteractive -NoProfile -Command "& {c:\temp\exit.ps1; exit $LastExitCode }"
    @echo From Cmd.exe: Exit.ps1 exited with exit code %errorlevel%

    Executing c:\temp\testexit.cmd results in the following output:

    Exiting with code 12345
    From Cmd.exe: Exit.ps1 exited with exit code 12345

    But now we want to call it from another PowerShell script, by executing PowerShell:

    c:\temp\testexit.ps1:

    PowerShell -NonInteractive -NoProfile -Command c:\temp\exit.ps1
    Write-Host "From PowerShell: Exit.ps1 exited with exit code $LastExitCode"

    Executing c:\temp\testexit.ps1 results in the following output:

    Exiting with code 12345
    From PowerShell: Exit.ps1 exited with exit code 1

    This is not what we expected… What happs? If the script just returns the exit code is 0, otherwise the exit code is 1, even if you exit with an exit code!?

    But what if we call the script directly, instead of through the PowerShell command?

    We change exit.ps1 to:

    Write-Host "Global variable value: $globalvariable"
    Write-Host "Exiting with code 12345"
    exit 12345

    And we change testexit.ps1 to:

    $global:globalvariable = "My global variable value"
    & c:\temp\exit.ps1
    Write-Host "From PowerShell: Exit.ps1 exited with exit code $LastExitCode"

    Executing c:\temp\testexit.ps1 results in the following output:

    Global variable value: My global variable value
    Exiting with code 12345
    From PowerShell: Exit.ps1 exited with exit code 12345

    This is what we wanted! But now we are executing the script exit.ps1 in the context of the testexit.ps1 script, the globally defined variable $globalvariable is still known. This is not what we want. We want to execute it is isolation.

    We change c:\temp\testexit.ps1 to:

    $global:globalvariable = "My global variable value"
    PowerShell -NonInteractive -NoProfile -Command c:\temp\exit.ps1
    Write-Host "From PowerShell: Exit.ps1 exited with exit code $LastExitCode"

    Executing c:\temp\testexit.ps1 results in the following output:

    Global variable value:
    Exiting with code 12345
    From PowerShell: Exit.ps1 exited with exit code 1

    We are not executing exit.ps1 in the context of testexit.ps1, which is good. But how can we reach the holy grail:

    1. Write a PowerShell script that can be executed from batch scripts an from PowerShell
    2. That return a specific error code
    3. That can specified as a string
    4. Can be executed both in the context of a calling PowerShell script AND (through a call to PowerShell) in it’s own execution space

    We change c:\temp\testexit.ps1 to:

    $global:globalvariable = "My global variable value"
    PowerShell -NonInteractive -NoProfile -Command  { c:\temp\exit.ps1 ; exit $LastExitCode }
    Write-Host "From PowerShell: Exit.ps1 exited with exit code $LastExitCode"

    This is the same approach as when we called it from the batch script. Executing c:\temp\testexit.ps1 results in the following output:

    Global variable value:
    Exiting with code 12345
    From PowerShell: Exit.ps1 exited with exit code 12345

    This is close. But we want to be able to specify the command to be executed as string, for example:

    $command = "c:\temp\exit.ps1 -param1 x -param2 y"

    We change c:\temp\exit.ps1 to: (support for variables, test if in its own context)

    param( $param1, $param2)
    Write-Host "param1=$param1; param2=$param2"
    Write-Host "Global variable value: $globalvariable"
    Write-Host "Exiting with code 12345"
    exit 12345

    If we change c:\temp\testexit.ps1 to:

    $global:globalvariable = "My global variable value"
    $command = "c:\temp\exit.ps1 -param1 x -param2 y"
    Invoke-Expression -Command $command
    Write-Host "From PowerShell: Exit.ps1 exited with exit code $LastExitCode"

    We get a good exit code, but we are still executing in the context of testexit.ps1.

    If we use the same trick as in calling from a batch script, that worked before?

    We change c:\temp\testexit.ps1 to:

    $global:globalvariable = "My global variable value"
    $command = "c:\temp\exit.ps1 -param1 x -param2 y"
    PowerShell -NonInteractive -NoProfile -Command { $command; exit $LastErrorLevel }
    Write-Host "From PowerShell: Exit.ps1 exited with exit code $LastExitCode"

    Executing c:\temp\testexit.ps1 results in the following output:

    From PowerShell: Exit.ps1 exited with exit code 0

    Ok, lets use the Invoke-Expression again. We change c:\temp\testexit.ps1 to:

    $global:globalvariable = "My global variable value"
    $command = "c:\temp\exit.ps1 -param1 x -param2 y"
    PowerShell -NonInteractive -NoProfile -Command { Invoke-Expression -Command $command; exit $LastErrorLevel }
    Write-Host "From PowerShell: Exit.ps1 exited with exit code $LastExitCode"

    Executing c:\temp\testexit.ps1 results in the following output:

    Cannot bind argument to parameter 'Command' because it is null.
    At :line:3 char:10
    + PowerShell <<<<  -NonInteractive -NoProfile -Command { Invoke-Expression -Command $command; exit $LastErrorLevel }

    From PowerShell: Exit.ps1 exited with exit code 1

    We should go back to executing the command as a string, so not within brackets (in a script block). We change c:\temp\testexit.ps1 to:

    $global:globalvariable = "My global variable value"
    $command = "c:\temp\exit.ps1 -param1 x -param2 y"
    PowerShell -NonInteractive -NoProfile -Command $command
    Write-Host "From PowerShell: Exit.ps1 exited with exit code $LastExitCode"

    Executing c:\temp\testexit.ps1 results in the following output:

    param1=x; param2=y
    Global variable value:
    Exiting with code 12345
    From PowerShell: Exit.ps1 exited with exit code 1

    Ok, we can execute the specified command text as if it is a PowerShell command. But we still have the exit code problem, only 0 or 1 is returned.

    Lets try something completely different. We change c:\temp\exit.ps1 to:

    param( $param1, $param2)

    function ExitWithCode
    {
        param
        (
            $exitcode
        )

        $host.SetShouldExit($exitcode)
        exit
    }

    Write-Host "param1=$param1; param2=$param2"
    Write-Host "Global variable value: $globalvariable"
    Write-Host "Exiting with code 12345"
    ExitWithCode -exitcode 12345
    Write-Host "After exit"

    What we do is specify to the host the exit code we would like to use, and then just exit, all in the simplest utility function.

    Executing c:\temp\testexit.ps1 results in the following output:

    param1=x; param2=y
    Global variable value:
    Exiting with code 12345
    From PowerShell: Exit.ps1 exited with exit code 12345

    Ok, this fulfills all our holy grail dreams! But couldn’t we make the call from the batch script also simpler?

    Change c:\temp\testexit.cmd to:

    @PowerShell -NonInteractive -NoProfile -Command "c:\temp\exit.ps1 -param1 x -param2 y"
    @echo From Cmd.exe: Exit.ps1 exited with exit code %errorlevel%

    Executing c:\temp\testexit.cmd results in the following output:

    param1=x; param2=y
    Global variable value:
    Exiting with code 12345
    From Cmd.exe: Exit.ps1 exited with exit code 12345

    This is even simpler! We can now just call the PowerShell code, without the exit $LastExitCode trick!

    ========================= CONCLUSIONS ============================

    And now the conclusions after this long long story, that took a lot of time to find out (and to read for you):

    • Don’t use exit to return a value from PowerShell code, but use the following function:
    • function ExitWithCode
      {
          param
          (
              $exitcode
          )

          $host.SetShouldExit($exitcode)
          exit
      }

    • Call script from batch using:

    • PowerShell -NonInteractive -NoProfile -Command "c:\temp\exit.ps1 -param1 x -param2 y"
      echo %errorlevel%

    • Call from PowerShell with: (Command specified in string, execute in own context)
      $command = "c:\temp\exit.ps1 -param1 x -param2 y"
      PowerShell -NonInteractive -NoProfile -Command $command

      $LastExitCode contains the exit code
    • Call from PowerShell with: (Direct command, execute in own context)

      PowerShell -NonInteractive -NoProfile -Command { c:\temp\exit.ps1 -param1 x -param2 y }
    • $LastExitCode contains the exit code

    • Call from Powershell with: (Command specified in string, invoke in caller context)
    • $command = "c:\temp\exit.ps1 -param1 x -param2 y"
      Invoke-Expression -Command $command
      $LastExitCode contains the exit code

    • Call from PowerShell with: (Direct command, execute in caller context)

      & c:\temp\exit.ps1 -param1 x -param2 y

    • $LastExitCode contains the exit code