1

当我尝试在Windows 终端中使用 PowerShell使用命令设置环境变量时set test1=value1,我没有收到任何错误。但是,当我尝试使用该set命令检查所有环境变量时,我收到以下提示:

cmdlet Set-Variable at command pipeline position 1
Supply values for the following parameters:
Name[0]:

我读到在使用 PowerShell 时,您可以使用以下方式设置环境变量:

$Env:test1 = "value1";    

我想设置变量,以便在我的后端custom-environment-variables.json 存储一个名称,配置可以使用 config.get("test") 提取它。

custom-environment-variables.json

{
    "test": "test1",
}

但每次我尝试这个时,它都会说Error: Configuration property "test" is not defined

执行相同的 CMD 程序(直接或通过 Windows 终端)我没有遇到任何问题。有什么想法可能导致这种情况吗?

4

1 回答 1

1

首先,简单的部分:

我没有收到任何错误,但是当我尝试检查所有环境时。调用“set”的变量我得到以下提示:

这是因为setPowerShell 中的命令行为不同。Set-Variable它是 PowerShell cmdlet的别名。你可以看到这个Get-Alias

此外,PowerShell 变量不是环境变量。正如您所评论的,在 PowerShell 中设置环境变量的正确方法是:

$env:variablename = "value"

setPowerShell 中(获取所有环境变量及其值的列表)的等效命令是:

Get-ChildItem env:
# Or using the alias
dir env:
# Or using another alias
ls env:

这可以访问 PowerShell“环境提供程序”,它本质上(我的总结过于简单)是 PowerShell 提供的包含环境变量的“虚拟驱动器/文件系统”。您也可以在此处创建变量。

更多阅读: PowerShell Doc 中的about_Environment_Variables


至于config模块的核心问题,我无法重现。它在 PowerShell 和 CMD 中都能正常工作。因此,让我回顾一下我的结果,希望它能帮助您了解可能会有所不同。所有测试都是在 Windows 终端中执行的,尽管正如我们在评论中确定的那样,这对您来说是 PowerShell 与 CMD 的更多区别:

config\default.json

{
  "test": "Original Value"
}

config\custom-environment-variables.json

{
  "test": "test1"
}

test1没有变量集的 CMD :

node在 CMD 中运行:

> const config = require('config')
undefined
> config.get('test')
'Original Value'
>

test1带有变量集的 CMD :

退出节点,然后返回 CMD:

>set test1=Override
>node

在节点中:

Welcome to Node.js v14.16.1.
Type ".help" for more information.
> const config = require('config')
undefined
> config.get('test')
'Override'
>

test1没有变量集的 PowerShell :

Welcome to Node.js v14.16.1.
Type ".help" for more information.
> const config = require('config')
undefined
> config.get('test')
'Original Value'
>

test1带有变量集的 PowerShell :

在 PowerShell 中:

PS1> $env:test1="Override"
PS1> node

在节点中:

Welcome to Node.js v14.16.1.
Type ".help" for more information.
> const config = require('config')
undefined
> config.get('test')
'Override'
>

于 2022-02-23T21:36:02.370 回答