Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't .NET objects in PowerShell use the current directory?

Tags:

When you use a .NET object from PowerShell, and it takes a filename, it always seems to be relative to C:\Windows\System32.

For example:

[IO.File]::WriteAllText('hello.txt', 'Hello World') 

...will write C:\Windows\System32\hello.txt, rather than C:\Current\Directory\hello.txt

Why does PowerShell do this? Can this behaviour be changed? If it can't be changed, how do I work around it?

I've tried Resolve-Path, but that only works with files that already exist, and it's far too verbose to be doing all the time.

like image 778
Roger Lipscombe Avatar asked Jun 28 '12 13:06

Roger Lipscombe


People also ask

How do I change the default directory in PowerShell?

Simplest way is to open Windows Powershell and click on the down arrow in the title bar to go to the Settings (you can use Ctrl+, as well). Make a window wider so you can see all the Profiles on the left side. Click on Windows Powershell profile and set your startup directory. Click Save at the bottom and you are done.

How do you change drives in PowerShell?

To change the drive letter using PowerShell, we can use the Set−Partition command but before that, we need to know which drive letter to change. You can check the drive letter using Windows Explorer, Get−Partition, Gwmi win32_Logicaldisk, or Get−CimInstance Win32_Logicaldisk command.

How do I go back one directory in PowerShell?

2 or later you can do cd - to navigate to your previous directory. cd is the alias for Set-Location . Adding paramerter + or - goes forward or backward through your location history. +1 This is the best answer for modern users.


2 Answers

You can change .net working dir to powershell working dir:
[Environment]::CurrentDirectory = (Get-Location -PSProvider FileSystem).ProviderPath
After this line all .net methods like [io.path]::GetFullPath and [IO.File]::WriteAllText will work without problems

like image 108
Denis Bakharev Avatar answered Oct 14 '22 20:10

Denis Bakharev


The reasons PowerShell doesn't keep the .NET notion of current working directory in sync with PowerShell's notion of the working dir are:

  1. PowerShell working dirs can be in a provider that isn't even file system based e.g. HKLM:\Software
  2. A single PowerShell process can have multiple runspaces. Each runspace can be cd`d into a different file system location. However the .NET/process "working directory" is essentially a global for the process and wouldn't work for a scenario where there can be multiple working dirs (one per runspace).
like image 39
Keith Hill Avatar answered Oct 14 '22 21:10

Keith Hill