PowerShell FileInfo outputs file in child directory


Why is the output in this case not c:\source\temp\test.txt?


Ahh this often trips people up in PowerShell. Although PowerShell has the notion of a current directory, this is not the same as the current directory for the process. The reason being, a Windows process can only have one current directory whereas a PowerShell process may have multiple runspaces/pipelines each with their own current directory and the PowerShell current directory may not even be a file location.

.NET methods that take relative paths will be resolved against the process’s current directory. So to be safe, whenever calling into .NET methods, you should use fully resolved paths. You could do:

$PWD gets expanded inside the string (because of the double quotes) and its an automatic variable that always returns the current working directory. It actually returns a PathInfo object because the string it embeds may not always be the absolute physical path. If you use PSDrives (for example, I have a temp:\ drive mapped to my temp directory) you’ll need to be more explicit.

A PowerShell guru may have a more concise syntax. The above is admittedly pretty ugly.


PowerShell FileInfo outputs file in child directory by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply