Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use an environment variable in powershell command

I have an environment variable named GOPATH. In old style command shell I could run the command %GOPATH%\bin\hello like this:

enter image description here

Is there an equivalently simple command in Windows PowerShell?


EDIT

I am not trying to print the environment variable. I am trying to USE it.

The variable is set correctly:

C:\WINDOWS\system32> echo $env:gopath
C:\per\go

Now I want to actually use this in a command line call, and it fails:

C:\WINDOWS\system32> $env:gopath\bin\hello
At line:1 char:12
+ $env:gopath\bin\hello
+            ~~~~~~~~~~
Unexpected token '\bin\hello' in expression or statement.
    + CategoryInfo          : ParserError: (:) [],        ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedToken
like image 695
David Avatar asked Dec 28 '18 16:12

David


People also ask

How do I use an environment variable in PowerShell?

We can also access environment variables using the built-in variable called $env followed by a colon and the name of the environment variable. For example, instead of using Get-Item or Get-ChildItem and using the Env drive, I can save some keystrokes and instead simply specify $env:COMPUTERNAME.

How do I see environment variables in PowerShell?

Select System. Select Advanced System Settings. Go to the Advanced tab. Select Environment Variables....

How do I reference an environment variable from the command line?

To list all the environment variables, use the command " env " (or " printenv "). You could also use " set " to list all the variables, including all local variables. To reference a variable, use $varname , with a prefix '$' (Windows uses %varname% ).


3 Answers

Use $env:[Variablename]

For example:

$env:Appdata

or

$env:COMPUTERNAME

using your example:

$env:GOPATH

To use this to execute a script use

& "$env:GOPATH\bin\hello"
like image 127
Jansen McEntee Avatar answered Oct 20 '22 21:10

Jansen McEntee


Using an environment variable in a path to invoke a command would require either dot notation or the call operator. The quotation marks expand the variable and the call operator invokes the path.

Dot Notation

. "$env:M2_Home\bin\mvn.cmd"

Call Operator

& "$env:M2_Home\bin\mvn.cmd"

like image 4
Dejulia489 Avatar answered Oct 20 '22 22:10

Dejulia489


One solution is to use start-process -NoNewWindow to run it.

C:\windows\system32> start-process -nonewwindow $env:gopath\bin\hello.exe
C:\windows\system32Hello, Go examples!
>

This is much more verbose obviously and puts the command prompt at an odd looking prompt: >. But it does work.

like image 1
David Avatar answered Oct 20 '22 21:10

David