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.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 newPathvalue, which your Go program would then have to set for itself, in its own (process-scoped) environment.