Search code examples
gocmdoperating-systemexecsystem-information

Error in executing a command in golang


I tried to get the OS name in Golang The below is my code.

// GetOsName.go
package main

import (
    "fmt"
    "os/exec"
)

func main() {
    fmt.Println("systeminfo","|","findstr","/B","/C:\"OS Name\"")
    Out,err:=exec.Command("systeminfo","|","findstr","/B","/C:\"OS Name\"").Output()
    if err!=nil{
        fmt.Println("Err:",err)
    }else{
        fmt.Println("Out:",string(Out))
    }
}

But when i execute the code i get this message

systeminfo | findstr /B /C:"OS Name"
Err: exit status 1

The command is right. When i try to execute the command in separate it works fine. Help me to solve this Thanks in Advance.


Solution

  • Your command is not right. Your command is shell code and cannot be executed except by a shell (here cmd.exe). If you really want to get the OS name like this: Execute cmd.exe with your command as an argument. You might consider executing systeminfo.exe and parsing the output in Go (instead of the shell).