Mike Christensen
Mike Christensen

Reputation: 91686

Push-Location command in PowerShell doesn't recognize newly created drive names

I'm having some issues with creating new drive labels through a script. I've isolated the problem down to a few lines to reproduce the issue.

First, create a file called Test.ps1:

New-PSDrive -name Foo -PSProvider FileSystem -root "C:\Code"
Set-Location Foo:\

You can change C:\Code with any directory that exists.

Next, on the PowerShell command line, run:

.\Test.ps1

Followed by:

Push-Location Foo:\

The error I'm getting is:

Push-Location : Cannot find drive. A drive with the name 'Foo' does not exist.
At line:1 char:14
+ Push-Location <<<<  Foo:\
    + CategoryInfo          : ObjectNotFound: (Foo:String) [Push-Location], DriveNotFoundException
    + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.PushLocationCommand

enter image description here

It's as if the Push-Location stack caches all the drive labels when the shell is initialized, and the New-PSDrive command doesn't update that cache. Is there any way to work around this bug, or force this stale data to update? Thanks!

Upvotes: 0

Views: 1424

Answers (2)

Mike Zboray
Mike Zboray

Reputation: 40838

Normally a called script or function is run in a new scope, so variables, functions, and drives defined in that scope are not accessible in outer scopes unless they are explicitly added to the global scope.

You can explicitly add the drive to the global scope, as you've mentioned, with the Scope parameter on New-PSDrive. There are several cmdlets and functions that have a scope parameter. Use get-help * -Parameter Scope to find them.

Another option is to run the script in the current scope using the dot source notation:

. .\Test.ps1

Upvotes: 1

Mike Christensen
Mike Christensen

Reputation: 91686

Found the solution:

New-PSDrive -name Foo -PSProvider FileSystem -root "C:\Code" -Scope Global

Setting -Scope Global fixes the problem.

Upvotes: 1

Related Questions