I am struggling to get the output for a Windows command that has a pipe in it. Here is the command:
systeminfo | findstr /B /C:"OS Name"
Here is the code:
c1 := exec.Command("systeminfo")
c2 := exec.Command("findstr", "/B", `/C:"OS Name"`)
r, w := io.Pipe()
c1.Stdout = w
c2.Stdin = r
var b2 bytes.Buffer
c2.Stdout = &b2
c1.Start()
c2.Start()
c1.Wait()
w.Close()
c2.Wait()
io.Copy(os.Stdout, &b2)
fmt.Println(b2)
Output: []
If I copy/paste the command in cmd, it will return results. Not sure why I can't get that reflected in my Go programme. I tried several variants, including the addition of "cmd", "/C" in the first command but no success either.
CodePudding user response:
Remove the io.Copy
to no redirect to STDOUT and print the content of the buffer.
systemCmd := exec.Command("systeminfo")
findCmd := exec.Command("findstr", "/B", "/C:OS Name")
reader, writer := io.Pipe()
buf := bytes.NewBuffer(nil)
systemCmd.Stdout = writer
findCmd.Stdin = reader
findCmd.Stdout = buf
systemCmd.Start()
findCmd.Start()
systemCmd.Wait()
writer.Close()
findCmd.Wait()
reader.Close()
fmt.Println(">>" buf.String())
ie:
PS C:\Users\user\Documents> go run .\main.go
>>OS Name: Microsoft Windows 10 Pro