New-PSDrive 在脚本和控制台中的不同行为

Different behaviour of New-PSDrive in script and console

我在使用 powershell 时遇到了一个小问题,这可能非常简单...如果我从控制台 运行 命令而不是从 .ps1 文件发出命令,我会得到不同的行为。命令;

New-PSDrive -PSProvider FileSystem -Name X -Root \computer_name\x -Persist

如果我从控制台 运行 它,我会得到我想要的行为,即出现在文件管理器中的永久 X: 驱动器。如果我 运行 它来自一个脚本,它只包含这一行,我就没有永久驱动器。

有什么想法吗?

-Scope Global 添加到您的 New-PSDrive 参数中。

New-PSDrive -PSProvider FileSystem -Name X -Root \computer_name\x -Persist -Scope Global

documentation, by default, scope is local. If you read about_Scope 中所述,您会看到本地表示当前范围,对于脚本来说,就是脚本本身。