简体   繁体   中英

How to use an environment variable in PowerShell console?

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

在此处输入图像描述

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

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"

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"

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.

Just a big huge THANK YOU! Your are the only one I found talking about that:

"To use this to execute a script use"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM