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

1
  • 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. Commented Jan 16, 2022 at 20:01

0

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.