开发者

PowerShell FileInfo outputs file in child directory

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜