William Bartholomew

Musings on software engineering, technology and Aspergers Syndrome.

PowerShell Drives

with one comment

I’ve been reading Pro Windows PowerShell recently, which is without a doubt the best book on the subject I’ve found. One of the cool things about PowerShell is that you can define your own drives that aren’t restricted to a single character name, think Subst on steroids.

I was inspired by this and decided it would be useful to have a script that maps my most commonly used directories to drives. So I created the following script:

$Drives = @{
    "dev"="C:\Dev\";
    "docs"="C:\Users\WilliamB\Documents\";
    "utils"="C:\Utils\";
    "drops"="\\server\devdrops\"
}

foreach ($Name in $Drives.Keys) {
    $null = New-PSDrive -PSProvider FileSystem -Name $Name -Root $Drives.$Name -Scope Global
    Invoke-Expression "function global:$($Name): { Push-Location $($Name): }"
}

The first part of this script creates a hashtable of drive name and destination path, for example, I want the drive dev mapped to C:\Dev\.

The second part of the script loops through each of the keys (drive names) in the hashtable and:

  1. Creates a new FileSystem drive named after the key ($Name) and rooted at the value ($Drives.$Name). The scope is set to global otherwise when the script finishes executing the drive will be removed.
  2. Defines a function called $Name: that changes directory to the drive we created. By default, you can’t type a drive name followed by colon to change to that drive like you can for C:, D:, etc. so we mimic this behaviour by defining a global function named $Name:.

These drives will only exist in the PowerShell session, so if you want them to be available every time you run PowerShell then you’ll need to execute this script from your PowerShell profile script. Run Get-Help profile to learn how to do this.

Written by wbarthol

August 25, 2009 at 9:03 am

Posted in sysadmin

One Response

Subscribe to comments with RSS.

  1. [...] a comment » I recently posted a script to map local and remote directories to PowerShell drives. Because this script executes when you open a new PowerShell session if you open it while [...]


Leave a Reply