8

How can I set value of environment variable and execute command in one line in PowerShell?

I have this:

PGPASSWORD=db_pass psql -U db_user -d db_name -a -h localhost -f some.sql

and it's working great in Linux.

How can I translate above to PowerShell command which will work on Windows Server 2012 - Windows 10?

I tried:

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

and I get error: "The & is reserved for future use..." - Windows 2012.

2 Answers 2

6

Try this:

$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

In reality this is two commands separated by a semi-colon so they can be run as a single line.

Note also that from PowerShell you set environment variables via $env:<name of var>.

Sign up to request clarification or add additional context in comments.

2 Comments

Actually this isn't exactly the equivalent of the bash command the question is about because it leaves the environment variable in place after the command is called. In the bash command, PGPASSWORD disappears after the call to psql.
Yeap, important difference. This was tripping me up because i still had some stuff set.
0

just add a trailing command to the compound list: ;$env:PGPASSWORD='' to get "C:\Program Files (x86)\PostgreSQL\9.4\bin\psql.exe" -U postgres -a -d db_name -h localhost -f some.sql; $env:PGPASSWORD=''

you might have to pipe add a sleep in there between the command and last reset of the variable, if the command is launched in asynchronous fashion otherwise you might end up resetting the variable before its use by the launched program. Mileage may vary. It's a hack, but it works better than leaving the password in the environment forever.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.