Thursday, November 9, 2017

PowerShell surprise: script current directory is not the process current directory

PowerShell supports paths expressed relatively to the current directory. You can do things like gc .\mydoc.txt to get the contents of mydoc.txt in the current directory. Sometimes, though, using relative paths will mysteriously fail with a file-not-found error. This happens when a .NET I/O function is called before the path is resolved by PowerShell. Changing the current directory in script (the one that displays at the prompt) doesn't necessarily affect the process's current directory, which you can get with [System.IO.Directory]::GetCurrentDirectory().

Most commonly, the problem is that a script calls a .NET Framework function directly, but some third-party modules may forget to do the resolution before trying to use the path. To set the process's current directory, you can use [System.IO.Directory]::SetCurrentDirectory.

No comments:

Post a Comment