0
func New() *PowerShell {
    ps, err := exec.LookPath("powershell.exe")
    if err != nil {
        panic(err)
        return nil
    }
    return &PowerShell{
        PowerShell: ps,
    }
}

func (ps *PowerShell) exec(args ...string) (stdOut string, stdErr string, err error) {
    args = append([]string{"-NoProfile", "-NonInteractive"}, args...)
    cmd := exec.Command(ps.PowerShell, args...)

    var stdout bytes.Buffer
    var stderr bytes.Buffer
    cmd.Stdout = &stdout
    cmd.Stderr = &stderr

    err = cmd.Run()
    stdOut, stdErr = stdout.String(), stderr.String()
    return
}

func RefreshEnv() bool {
    ps := New()

    cmdString := `$env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User")`
    stdOut, stdErr, err := ps.exec(cmdString)

    if stdErr != "" || err != nil {
        fmt.Println(stdErr)
        fmt.Println(err.Error())
        return false
    }
    fmt.Println(stdErr)
    fmt.Println(stdOut)
    return true
}

Running the above golang code can't refresh environment variable.

But run

$env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User")

in powershell can work. What resons for this? How can I reload the path from PowerShell.

(I'm sorry for my poor English. Look forward and thanks for your answer )

Powershell: Reload the path in PowerShell

miaotiao
  • 1
  • 2
  • You're performing the refresh _in a child process_ (`powershell.exe`). Environment variables are exclusive to each process (though a child process usually _inherits copies of_ the caller's variables), so you Go program's own environment won't change. You can either refresh your Go program's own environment before calling PowerShell (which will inherit the changes), or let PowerShell _output_ the new `Path` value, which your Go program would then have to set for itself, in its own (process-scoped) environment. – mklement0 Jan 16 '22 at 20:01

0 Answers0