How to execute a simple Windows command in Golang?

后端 未结 6 1973
执念已碎
执念已碎 2020-12-08 10:06

How to run a simple Windows command?

This command:

exec.Command(\"del\", \"c:\\\\aaa.txt\")

.. outputs th

6条回答
  •  盖世英雄少女心
    2020-12-08 11:07

    Ok let's see, according to the documentation, in windows, processes receive commands as a single line string and do some parsing of their own. Exec's Command function builds the command string by combining all arguments together using CommandLineToArgvW, that despite being the most common quoting algorithm doesn't work for every application. Applications like msiexec.exe and cmd.exe use an incompatible unquoting algorithm, hence the extra mile. Heres a different example using powershell

    package main
    
    import (
            "os/exec"
            "fmt"
            "log"
            )
    func main() {
         out, err := exec.Command("powershell","remove-item","aaa.txt").Output()
         if err != nil {
             log.Fatal(err)
         } else {
             fmt.Printf("%s",out)
         }
    

提交回复
热议问题