Skip to content
Menu
The Lonely Administrator
  • PowerShell Tips & Tricks
  • Books & Training
  • Essential PowerShell Learning Resources
  • Privacy Policy
  • About Me
The Lonely Administrator

New-PSDriveHere

Posted on August 30, 2010August 30, 2010

I spend a lot of time, as you might expect, at a PowerShell prompt. Especially when training, presenting or doing demonstrations. Very often I'm in a folder with a long path like PS C:\users\jeff\Documents\Enterprise Mgmt Webinar. That takes up a lot of screen real estate and can be distracting. What I often will do is create a PSDrive for this folder. But that takes time. What I really need is a shortcut like a function with an alias. Here's what I came up with.
Creating a new PSDrive is not that difficult. You specify a drive name, which can be just about anything, a PSProvider, and a location. What I wanted was a way to take any path, from any provider, and add a PSDrive from the item's name. So if I had a path like C:\Files\Work, I would create a new PSDrive called Work:.
But what about a folder like ...Documents\Enterprise Mgmt Webinar? I decided that most likely I would want the last word. Although there might be occasions when I needed the first word. Finally, I wanted to be able to handle any PSProvider automatically. I ended up with a function called New-PSDriveHere.
[cc lang="PowerShell"]
Function New-PSDriveHere {

Manage and Report Active Directory, Exchange and Microsoft 365 with
ManageEngine ADManager Plus - Download Free Trial

Exclusive offer on ADManager Plus for US and UK regions. Claim now!

<# .Synopsis Create a new PSDrive at the current location. .Description This function will create a new PSDrive at the specified location. The default is the current location, but you can specify any PSPath. The function will take the last word of the path and use it as the name of the new PSDrive. If you prefer to use the first word of the location, use -First. .Parameter Path The path for the new PSDrive. The default is the current location. .Parameter First Use the first word of the current location for the new PSDrive. .Example PS C:\users\jeff\Documents\Enterprise Mgmt Webinar> new-psdrivehere

Name Used (GB) Free (GB) Provider Root CurrentLocation
---- --------- --------- -------- ---- ---------------
Webinar 146.57 FileSystem C:\users\jeff\Documents\Enter...
.Example
PS C:\users\jeff\Documents\Enterprise Mgmt Webinar> new-psdrivehere -first

Name Used (GB) Free (GB) Provider Root CurrentLocation
---- --------- --------- -------- ---- ---------------
Enterprise 146.57 FileSystem C:\users\jeff\Documents\Enter...
.Example
PS C:\> new-psdrivehere HKLM:\software\microsoft

Name Used (GB) Free (GB) Provider Root CurrentLocation
---- --------- --------- -------- ---- ---------------
microsoft Registry HKEY_LOCAL_MACHINE\software\micr...

.Inputs
None. You cannot pipe to this function.
.Outputs
System.Management.Automation.PSDrive
.Link
https://jdhitsolutions.com/blog

.Link
Get-PSDrive
New-PSDrive

.Notes
NAME: New-PSDriveHere
VERSION: 1.0
AUTHOR: Jeffery Hicks
LASTEDIT: August 27, 2010

Learn more with a copy of Windows PowerShell 2.0: TFM (SAPIEN Press 2010)

#>

[cmdletBinding(SupportsShouldProcess=$True)]

Param(
[Parameter(Position=0)]
[ValidateScript({Test-Path $_})]
[string]$Path=".",
[switch]$First
)

#get the specified location
$location=Get-Item -Path $path

if ($first) {
$pattern="^\w+"
}
else {
$pattern="\w+$"
}

#Make sure name contains valid characters. This function
#should work for all but the oddest named folders.
if ($location.Name -match $pattern) {
$name=$matches[0]

#verify a PSDrive doesn't already exist
Write-Verbose "Testing $($name):"
If (-not (Test-Path -path "$($name):")) {
Write-Verbose "Creating PSDrive for $name"
New-PSDrive -Name $name -PSProvider $location.PSProvider -Root $Path `
-Description "Created $(get-date)" -scope Global
}
else {
Write-Warning "A PSDrive for $name already exists"
}
}
else {
#The location has something odd about it
Write-Warning "$path doesn't meet the criteria"
}

} #function
[/cc]
The function takes any location as a parameter, but defaults to the current location. The only other parameter is -First, which tells the function to use the first matching word in the location. I use a regular expression pattern to match either the first or last word of the current location, anchored accordingly.
[cc lang="Powershell"]
$location=Get-Item -Path $path

if ($first) {
$pattern="^\w+"
}
else {
$pattern="\w+$"
}
[/cc]
I don't want to try to map a drive if it already exists, so I use Test-Path to verify.
[cc lang="PowerShell"]
Write-Verbose "Testing $($name):"
If (-not (Test-Path -path "$($name):")) {
[/cc]
If it exists then a warning message is displayed. Otherwise the function creates the new PSDrive. The function can automatically detect the PSProvider from the location by looking at the PSProvider property.
[cc lang="PowerShell"]
New-PSDrive -Name $name -PSProvider $location.PSProvider -Root $Path `
-Description "Created $(get-date)" -scope Global
[/cc]
Normally, the best practice is not to create out of scope items, but in this case that is the function's purpose so I used the -Scope parameter with New-PSDrive. The cmdlet by default writes the new PSDrive to the pipeline, so that is the function's output.
What's nice is that because the function supports cmdlet binding and SupportsShouldProcess is set to $True, if I run the function using -WhatIf, this is passed to New-PSDrive without any extra coding on my part.
[cc lang="PowerShell"]
PS C:\> new-psdrivehere $env:temp -whatif
What if: Performing operation "New Drive" on Target "Name: Temp Provider: Microsoft.PowerShell.Core\FileSystem Root: C:\Users\Jeff\AppData\Local\Temp".
PS C:\>
[/cc]
Finally, I created an alias so I could call this function very easily with a minimum of typing.
[cc lang="PowerShell"]
Set-Alias -Name npsd -Value New-PSDriveHere
[/cc]

Download the original version of New-PSDriveHere.ps1.

Update
As soon as I posted, I realized I was missing a useful feature. What if you didn't want to use anything in the current location name? Perhaps someone, myself included, might want a different name? So I went back and added a -Name parameter so you could specify something. I really should have made parameter sets, but it really doesn't matter. If you use -Name and -First, the latter will be ignored.

I also updated the online link to point to this blog post.

Download the latest version: New-PSDriveHere-v1.1.ps1


Behind the PowerShell Pipeline

Share this:

  • Click to share on X (Opens in new window) X
  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on Mastodon (Opens in new window) Mastodon
  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on Pocket (Opens in new window) Pocket
  • Click to share on Reddit (Opens in new window) Reddit
  • Click to print (Opens in new window) Print
  • Click to email a link to a friend (Opens in new window) Email

Like this:

Like Loading...

Related

2 thoughts on “New-PSDriveHere”

  1. Spundae says:
    August 30, 2010 at 9:08 am

    Very very useful, thank you. I am using this now to some UNC paths that are just too long. This way it makes it more readable.

    1. Jeffery Hicks says:
      August 30, 2010 at 9:28 am

      That’s great. And if you use them all the time, dot source my function and add the lines to your PowerShell profile.

Comments are closed.

reports

Powered by Buttondown.

Join me on Mastodon

The PowerShell Practice Primer
Learn PowerShell in a Month of Lunches Fourth edition


Get More PowerShell Books

Other Online Content

github



PluralSightAuthor

Active Directory ADSI Automation Backup Books CIM CLI conferences console Friday Fun FridayFun Function functions Get-WMIObject GitHub hashtable HTML Hyper-V Iron Scripter ISE Measure-Object module modules MrRoboto new-object objects Out-Gridview Pipeline PowerShell PowerShell ISE Profile prompt Registry Regular Expressions remoting SAPIEN ScriptBlock Scripting Techmentor Training VBScript WMI WPF Write-Host xml

©2025 The Lonely Administrator | Powered by SuperbThemes!
%d