Set-Location, and [Environment]::CurrentDirectory

One question that comes up frequently is, “Why does PowerShell not change its [System.Environment]::CurrentDirectory as I navigate around the shell?

One of the difficult aspects of this comes from the fact that PowerShell supports multiple pipelines of execution.  Although it’s not directly exposed yet, users will soon be able to suspend jobs to the background, and other concurrent tasks.

The current directory affects the entire process, so if we change the directory as you navigate around the shell, you risk corrupting the environment of jobs you have running in the background.

When you use filenames in .Net methods, the best practice is to use fully-qualified path names.  The Resolve-Path cmdlet makes this easy:

[C:\temp]
PS:37 > $reader = new-object System.Xml.XmlTextReader (Resolve-Path baseline.xml)
Suggestion: An alias for Resolve-Path is rvpa

[C:\temp]
PS:38 > $reader.BaseURI
file:///C:/temp/baseline.xml

If you wish to access a path that doesn’t already exist, use the Join-Path  cmdlet:

(Join-Path (Get-Location) newfile.txt)

2 Responses to “Set-Location, and [Environment]::CurrentDirectory”

  1. Steve writes:

    This reminds me of something I haven’t yet figured out how to do. It’s probably so simple I’ll feel like an idiot once I see how to do it (that’s why my last name is missing above – at least I’m the only person that will know that I’m an idiot).

    How do you add a directory to the path? Back in the DOS days it was easy but it’s not so obvious in Powershell.

    That’s not the only thing I can do in DOS but not in Powershell – here’s another: How do you change file attributes? How do you change a read-only file to writable?

    I LOVE Powershell and I hate to have to fall back to the DOS commands to do some of this stuff.

  2. Synchronize directories with a breakpoint « Sly PowerShell writes:

    […] with its $pwd (path of the current directory) automatic variable; Lee Holmes explains the reason here. Back in v1, the way to work around this was to set the Environment.CurrentDirectory value in your […]

Leave a Reply