Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell FileInfo outputs file in child directory

Tags:

powershell

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

PS C:\source\temp> (New-Object IO.FileInfo .\test.txt).FullName
c:\source\test.txt
like image 793
Eric Schoonover Avatar asked May 05 '10 01:05

Eric Schoonover


1 Answers

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:

PS> (New-Object IO.FileInfo "$PWD\test.txt").FullName

$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.

PS> (New-Object IO.FileInfo "$($PWD.ProviderPath)\test.txt").FullName

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

like image 189
Josh Avatar answered Nov 17 '22 20:11

Josh