Adding Personal Drives in PowerShell

by Sep 4, 2012

In a previous tip we showed you how you can add new drives to easily access your desktop, your cookies or media like music and video. However, when you call that code from within a function, your new drives are gone right after you created them:

function Add-PersonalDrive {
  [System.Enum]::GetNames([System.Environment+SpecialFolder]) | 
    ForEach-Object {
      $name = $_
      $target = [System.Environment]::GetFolderPath($_)
      New-PSDrive $name FileSystem $target
    }
}

So when you run this function and then look for the new drives, they are not there:

Add-PersonalDrive
Get-PSDrive

That's because PSDrives are scoped, so they go out of scope the moment the function exits. To assign global scope to PSDrives, add global scope:

function Add-PersonalDrive {
  [System.Enum]::GetNames([System.Environment+SpecialFolder]) | 
    ForEach-Object {
      $name = $_
      $target = [System.Environment]::GetFolderPath($_)
      New-PSDrive $name FileSystem $target -Scope Global
    }
}

Once you rerun the function, things work as expected:

Add-PersonalDrive
Dir Desktop:
Get-PSDrive

Twitter This Tip! ReTweet this Tip!