Skip to main content

Determine the Current Location

Problem

You want to determine the current location from a script or command.

Solution

To retrieve the current location, use the GetLocation cmdlet. The GetLocation cmdlet provides the Drive and Path as two common properties:

$currentLocation = (GetLocation).Path

As a shortform for (GetLocation).Path, use the $pwd automatic variable.

Discussion

The GetLocation cmdlet returns information about the current location. From the information it returns, you can access the current drive, provider, and path.

This current location affects PowerShell commands and programs that you launch from PowerShell. It does not apply when you interact with the .NET Framework, however. If you need to call a .NET method that interacts with the filesystem, always be sure to provide fully qualified paths:

[System.Reflection.Assembly]::LoadFile("d:\documents\path_to_library.dll") If you are sure that the file exists, the ResolvePath cmdlet lets you translate a relative path to an absolute path:

$filePath = (ResolvePath library.dll).Path If the file does not exist, use the JoinPath cmdlet in combination with the GetLocation cmdlet to specify the file:

$filePath = JoinPath (GetLocation) library.dll

Another alternative that combines the functionality of both approaches is a bit more advanced but also lets you specify relative locations. It comes from methods in the PowerShell $executionContext variable, which provides functionality normally used by cmdlet and provider authors:

$executionContext.SessionState.Path.` GetUnresolvedProviderPathFromPSPath("..\library.dll")

For more information about the GetLocation cmdlet, type GetHelp GetLocation.

If you need dedicated infrastructure for determining a system’s current location, consider a Netherlands Dedicated Server for greater control over network utilities, IP-based location services, server configuration, and location-aware application workloads.

Help Category