PowerShell boosting

The Windows PowerShell is quite good, but nothing is perfect. Here are some improvements.

The first thing we should do is install PsGet. This is like NuGet or Chocolatey, but for the PowerShell. It creates really useful package control commands. We open a PowerShell with administrative rights and run the following command:

(new-object Net.WebClient).DownloadString("http://psget.net/GetPsGet.ps1") | iex

There is much more we can do with PsGet, but the most useful command is certainly install-module.

Let's start by installing PSReadLine. PSReadLine represents a set of very useful extensions, that contain functionality such as syntax highlighting, preserving the history across sessions and more.

install-module PSReadline

Installed modules get loaded right away. Since we want to use the PSReadLine module every time we open a PowerShell, we should edit the file Microsoft.PowerShell_profile.ps1, usually located in the directory WindowsPowerShell of the user's Documents folder.

The following line should be added to the profile script:

import-module PSReadline

Alright. This already gives us a lot of cool features. Next we should install the PoshGit module, if we did not already. A more precise description is given in the references below.

An important note for Windows 7 (or older) users: There is a high probability that the installed PowerShell is too old for PSReadLine (or other modules). If you want to upgrade to PowerShell 3.0 (or newer), then go to http://www.microsoft.com/en-us/download/confirmation.aspx?id=34595. There are some updates available.

A pretty useful function is a pendant for the Linux tool touch.

Function Touch-File {
    $file = $args[0]

    if ($file -eq $null) {
        throw "No filename supplied"
    } elseif (Test-Path $file) {
        (Get-ChildItem $file).LastWriteTime = Get-Date
    } else {
        echo $null > $file
    }
}

This function should be placed in the profile. Additionally we might want to enhance our search experience. A nice option is to Install-Module Find-String. For instance we can then apply the following command to find all occurrences of the word form in all C# source files:

find-string form *.cs

Of course we also need to import the module in our profile as shown above.

A task that often appears is to find out what path leads to a specific command. This is particularly useful if we do not know which included path is responsible for delivering the command. Also we might not know which version is taken (what precedence is used).

Function Which {
    $command = $args[0]

    if ($command -eq $null) {
        throw "No command supplied"
    }

    Get-Command $command | Select-Object -ExpandProperty Definition
}
Created . Last updated .

References

Sharing is caring!