37

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
4
  • 1
    Use $Env:GOPATH Commented Dec 28, 2018 at 17:00
  • 2
    Possible duplicate of How to print environment variables to console in Powershell? Commented Dec 28, 2018 at 17:02
  • 4
    Not a duplicate. I am not trying to PRINT. I am trying to USE. Commented Dec 28, 2018 at 17:55
  • 1
    And when printing you don't use the var? Commented Dec 28, 2018 at 18:00

3 Answers 3

41

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"
Sign up to request clarification or add additional context in comments.

Comments

8

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"

1 Comment

The call operator had already been suggested. Using the dot-sourcing operator would work too, but that is only incidental. The operator is for running (PowerShell) scripts in the current context as opposed to running them in a child context via the call operator, but external commands are running in a separate process anyway, so there's no advantage in using . over &.
0

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.

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.