24

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
informatik01
  • 16,038
  • 10
  • 74
  • 104
David
  • 1,743
  • 1
  • 18
  • 25
  • 1
    Use `$Env:GOPATH` –  Dec 28 '18 at 17:00
  • 1
    Possible duplicate of [How to print environment variables to console in Powershell?](https://stackoverflow.com/questions/50861082/how-to-print-environment-variables-to-console-in-powershell) –  Dec 28 '18 at 17:02
  • 2
    Not a duplicate. I am not trying to PRINT. I am trying to USE. – David Dec 28 '18 at 17:55
  • And when printing you don't **use** the var? –  Dec 28 '18 at 18:00

3 Answers3

31

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"
Jansen McEntee
  • 451
  • 5
  • 9
7

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"

li ki
  • 342
  • 3
  • 11
Dejulia489
  • 1,165
  • 8
  • 14
  • 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 `&`. – Ansgar Wiechers Dec 28 '18 at 23:58
1

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.

David
  • 1,743
  • 1
  • 18
  • 25