Extending Visual Studio with PowerShell scripts

1 Flares Twitter 0 Facebook 0 LinkedIn 1 Filament.io Made with Flare More Info'> 1 Flares ×

Scratching an itch

While Visual Studio 2010 is a powerful tool, there are a few caveats to it. First off, if you require some additional functionality from it, then you have to rely on third party add-ins. The latter is a something of a blessing disquised in a curse, wrapped up in the venner of frustration. While I’m very appreciative of people that release free tools for everyone to use, the truth of the matter is I would rather pay for them -and suffer the Kafkaesque process of getting it approved to use by company IT departments-, than end up with a Visual Studio that crashes 5 times a day, just because I want to have colour formatted output.
Enter Powershell to help us with some tasks. What follows are three simple scripts that will allow you to view application log files in colour coded format, for easier spotting within large swaths of text, via an approximation to GNU’s tail command, and a simple script to completely clean the solution directory of all bin, obj sub-directories.

Set-up

First off you’ll need to be able to run these scripts from within VS, so I would recommend this process. I’ll assume you’ve done this step.

These scripts are best utilised within a version control system, such that your teammates can all share the same scripts and augment/correct them.

This script was born out of the necessity to do a full deep clean of the solution directory of all the bin and obj directories. The reason for that was that for some reason doing a full rebuild did not empty all of those directories. This way all folders that are named “bin”, and “obj”, except some which I’ll come back to later on, are removed. There is also a progress bar available to indicate how long it will take to do so, in the case there are quite a few of these files, and you don’t want to be left staring at a blinking cursor in a command line, wondering if it’s even started yet.

##################################################
function CleanProj
{
    <#
        .SYNOPSIS
        Recursively delete all directories named "bin" or obj"
        starting from the current directory
 
        .DESCRIPTION
        Find all directories and sub-directories from the current
        working directory and delete them
 
        .INPUTS
        None. You cannot pipe objects to Add-Extension.
 
        .OUTPUTS
        None.
 
        .EXAMPLE
        C:\PS> CleanProj
        .NOTES 
    Author     : Christos Delivorias
    Requires   : PowerShell V2 CTP3 
    #>
    cls
    write-host ""
    write-host ""
    write-host ""
    write-host ""
    write-host ""
    write-host ""
    write-host "Full clean of project folder has begun"
    write-progress -id 1 -activity "Cleaning the project folder" -Status "Acquiring list of files to delete. Please wait..."
    $ListOfFiles = Get-ChildItem ./ -recurse | Where-Object {$_.Name -eq "bin" -or
                                                            $_.Name -eq "obj" -or
                                                            $_.Name -eq "Market Conventions" -or
                                                            $_.FullName -like "*QDA Data\Models*"-and
                                                            $_.FullName -notlike "*Third Party*"}
 
    for ($i = 1; $i -lt $ListOfFiles.Count; $i++)
    {
        write-progress -id 1 -activity "Deleting Files..." -Status $ListOfFiles[$i].FullName -PercentComplete (($i / $ListOfFiles.Count)*100);
        Remove-Item -Path $ListOfFiles[$i].FullName -Force -Recurse #-WhatIf
    }
    write-progress -id 1 -activity "Cleaning the project folder" -status "Full clean of project folder is complete"
    write-host "Full clean of project folder is complete"
}
 
#$sw = [Diagnostics.Stopwatch]::StartNew()
CleanProj
#$sw.Stop()
#write-host $sw.Elapsed
#Write-Host "Press any key to continue ..."
#$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

I also have some optionality to exclude certain filename – e.g. for third party binaries; see the highlighted code – and also to run this in a dry run mode with the whatif flag, where deletions are not actually taking place, but the filepaths of each file that would be deleted is printed on the terminal.

The following is a script attempting to mimic as closely as possible the behavior of GNU Tail and also follow any new lines added to a file. The case study for this script is when using log4net to log error, debug, and status information of your application. Ideally you’d like to be able to easily view if an ERROR, or WARN flag has showed up in your log files. This gets trickier if you’re generating generous amounts of log entries and thus the file scrolls off the screen quite quickly. By running the script below, you can assign a colour of severity to each of the keywords. At line 28 you can see where you can add more words to look for. You can also change the colour preferences. I’m using a simple traffic light scheme, but you can change the colours, by just providing a new colour name.

param([String]$filepath)
#################################################
function tail ($file)
{
    <#
        .SYNOPSIS
        tail is a PowerShell function used to display the tail end of a text file
 
        .INPUTS
        The name or filepath of the file to monitor
 
        .OUTPUTS
        The last part of the file and any subsequent content added to it
 
        .EXAMPLE
        C:\PS> tail filename.txt
        .NOTES 
        This function will run continuisly until interrupted by pressing Ctrl-C in this window
 
    Author     : Christos Delivorias
    Requires   : PowerShell V2 CTP3 
    #>
    gc -wait $file |
        ForEach-Object {
            if ($_.Contains("ERROR")) {Write-ColorOutput red ($_)}
                elseif ($_.Contains("WARN")) {Write-ColorOutput yellow ($_)}
                    elseif ($_.Contains("DEBUG") -or $_.Contains("INFO")) {Write-ColorOutput green ($_)}
                        # elseif ($_.Contains("OTHER")) {Write-ColorOutput darkblue ($_)}
                        else {Write-Host $_}
            }    
}
 
 
################ Helper Functions ###################   
function Write-ColorOutput($ForegroundColor)
{
    # save the current color
    $fc = $host.UI.RawUI.ForegroundColor
 
    # set the new color
    $host.UI.RawUI.ForegroundColor = $ForegroundColor
 
    # output
    if ($args) {
        Write-Output $args
    }
    else {
        $input | Write-Output
    }
 
    # restore the original color
    $host.UI.RawUI.ForegroundColor = $fc
}
 
tail($filepath)

Wrap-up

That’s it for now. I’m really interested if you have any suggestions on PS scripts that you use in daily development.
Let me know in the comments.

Update

I’ve found this brilliant process, which allows you to tunnel all internet traffic via a private VPN connection. Encrypt all your traffic from prying eyes

Run all online traffic through an PPTP VPN connection

1 Flares Twitter 0 Facebook 0 LinkedIn 1 Filament.io Made with Flare More Info'> 1 Flares ×