传递节点envvariables与Windows PowerShell

我试图像这样通过一个envvariables节点与powershell

C:\Users\everton\my-project>$env:MY_VAR = 8000 node index.js 

但获取PowerShell的错误

令牌“节点”意外的expression或声明

首先设置环境变量MY_VAR并像这样运行你的应用程序。

 C:\Users\everton\my-project> $env:MY_VAR="8000" ; node index.js 

你可以通过访问index.js的环境变量MY_VAR

process.env.MY_VAR

…或者你只是写出obscure-wtf-language-scripting的痛苦,并使用命令作用域(加上跨平台)的node.js脚本之一:

  • cross-env (内联)

     > cross-env MYVAR=MYVALUE node index.js 
  • env-cmd (来自.env文件)

     > env-cmd .env node index.js 

     #.env file MYVAR=MYVALUE 

为了补充Harikrishnan的有效答案 :

PowerShell与传递POSIX-like shell提供的环境变量的命令范围方法没有任何 相同之处 , 例如:

  # Eg, in Bash: # Define environment variable MY_VAR for the child process being invoked (`node`) # ONLY; in other words: MY_VAR is scoped to the command being invoked # (subsequent commands do not see it). MY_VAR=8000 node index.js 

在PowerShell中,正如Harikrishnan的答案所示,您必须首先定义环境变量,然后在单独的语句中调用子进程,以便$env:MY_VAR="8000"; node index.js $env:MY_VAR="8000"; node index.js 正确的PowerShell解决方案,但是$env:MY_VAR 保留在会话剩余部分的范围内 (它在进程级别设置)。

请注意,甚至使用用&调用的脚本块来创建子范围在这里没有帮助,因为这样的子范围只适用于PowerShell变量,而不适用于环境变量。

当然,您可以在node调用后手动删除环境变量:
Remove-Item env:MY_VAR

或者,使用助手功能 – 见下文。


辅助函数用于命令作用域的环境修改。

如果您定义了下面的帮助函数(请记住函数定义必须放在被调用之前 ),您可以通过以下方式实现命令作用域的环境修改:

 # Invoke `node index.js` with a *temporarily* set MY_VAR environment variable. Invoke-WithEnvironment @{ MY_VAR = 8000 } { node index.js } 

Invoke-WithEnvironment() 源代码

 function Invoke-WithEnvironment { <# .SYNOPSIS Invokes commands with a temporarily modified environment. .DESCRIPTION Modifies environment variables temporarily based on a hashtable of values, invokes the specified script block, then restores the previous environment. .PARAMETER Environment A hashtable that defines the temporary environment-variable values. Assign $null to (temporarily) remove an environment variable that is currently set. .PARAMETER ScriptBlock The command(s) to execute with the temporarily modified environment. .EXAMPLE > Invoke-WithEnvironment @{ PORT=8080 } @{ node index.js } Runs node with environment variable PORT temporarily set to 8080, with its previous value, if any #> param( [Parameter(Mandatory)] [System.Collections.IDictionary] $Environment, [Parameter(Mandatory)] [scriptblock] $ScriptBlock ) # Modify the environment based on the hashtable and save the original # one for later restoration. $htOrgEnv = @{} foreach ($kv in $Environment.GetEnumerator()) { $htOrgEnv[$kv.Key] = (Get-Item -EA SilentlyContinue "env:$($kv.Key)").Value Set-Item "env:$($kv.Key)" $kv.Value } # Invoke the script block try { & $ScriptBlock } finally { # Restore the original environment. foreach ($kv in $Environment.GetEnumerator()) { # Note: setting an environment var. to $null or '' *removes* it. Set-Item "env:$($kv.Key)" $htOrgEnv[$kv.Key] } } }