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.
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.
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.
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.
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
The reasons PowerShell doesn't keep the .NET notion of current working directory in sync with PowerShell's notion of the working dir are:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With