Adding Personal Drives

Share |

Join PowerShell.com!
Subscribe to Feed

PowerShell eBook
Sign up for
Your PowerTip of the Day:

Powershell Plus


13 Free SQL Tools from Idera


Free Ebook: Mastering Powershell

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!


Posted Aug 02 2011, 06:00 AM by ps1
Copyright 2012 PowerShell.com. All rights reserved.