为什么 PowerShell 中的 .NET 对象不使用当前目录? [英] Why don't .NET objects in PowerShell use the current directory?
问题描述
当您使用 PowerShell 中的 .NET 对象并且它采用文件名时,它似乎总是与 C:\Windows\System32
相关.
When you use a .NET object from PowerShell, and it takes a filename, it always seems to be relative to C:\Windows\System32
.
例如:
[IO.File]::WriteAllText('hello.txt', 'Hello World')
...将写入 C:\Windows\System32\hello.txt
,而不是 C:\Current\Directory\hello.txt
...will write C:\Windows\System32\hello.txt
, rather than C:\Current\Directory\hello.txt
为什么 PowerShell 会这样做?这种行为可以改变吗?如果无法更改,我该如何解决?
Why does PowerShell do this? Can this behaviour be changed? If it can't be changed, how do I work around it?
我已经尝试过 Resolve-Path
,但这只适用于已经存在的文件,而且它太冗长了,无法一直执行.
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.
推荐答案
PowerShell 没有将当前工作目录的 .NET 概念与 PowerShell 的工作目录概念保持同步的原因是:
The reasons PowerShell doesn't keep the .NET notion of current working directory in sync with PowerShell's notion of the working dir are:
- PowerShell 工作目录可以位于甚至不是文件系统的提供程序中基于例如HKLM:\软件
- 单个 PowerShell 进程可以拥有多个运行空间.每个运行空间都可以 cd`d 到不同的文件中系统位置.但是 .NET/process 工作目录"是本质上是流程的全局变量,不适用于可以有多个工作目录(每个运行空间一个)的场景.
这篇关于为什么 PowerShell 中的 .NET 对象不使用当前目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!