如何在一行(PowerShell)中设置环境变量并执行命令?

BPS*_*BPS 6 bash powershell environment-variables

如何在PowerShell中在一行中设置环境变量的值并执行命令?

我有这个:

PGPASSWORD=db_pass psql -U db_user -d db_name -a -h localhost -f some.sql
Run Code Online (Sandbox Code Playgroud)

它在 Linux 中运行良好。

如何将上述转换为适用于 Windows Server 2012 - Windows 10 的 PowerShell 命令?

我试过:

SET "PGPASSWORD=db_pass" & "C:\Program Files (x86)\PostgreSQL\9.4\bin\psql.exe" -U postgres -a -d db_name -h localhost -f some.sql
Run Code Online (Sandbox Code Playgroud)

我收到错误消息:“& 保留供将来使用...” - Windows 2012。

Mar*_*agg 6

尝试这个:

$env:PGPASSWORD='db_pass'; & "C:\Program Files (x86)\PostgreSQL\9.4\bin\psql.exe" -U postgres -a -d db_name -h localhost -f some.sql
Run Code Online (Sandbox Code Playgroud)

实际上,这是由分号分隔的两个命令,因此它们可以作为一行运行。

另请注意,在 PowerShell 中,您可以通过$env:<name of var>.

  • 实际上,这并不完全等同于问题所涉及的 bash 命令,因为它在调用命令后将环境变量保留在适当的位置。在 bash 命令中,“PGPASSWORD”在调用 psql 后消失。 (5认同)