How to run WSL command without opening CMD Window
How can I hide the CMD windows that opens when I run a WSL command? I tried the following, but the command object is missing the attribute for hidden window flag. My goal is to run a WSL command without opening a CMD window on Windows 11. Thanks.
// Get the command
cmd := distro.Command(context.Background(), command)
// Ensure to hide the window
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true} // This fails to compile
// Run wsl command and get output
out, err := cmd.CombinedOutput()
if err != nil {
fmt.Fprintf(os.Stderr, "Unexpected error: %v\nError message: %s", err, out)
return errors.New("Error: Failed to run command: " + fmt.Sprintf("Unexpected error: %v\nError message: %s", err, out))
} else {
pp.Println("WSL: " + string(out))
return nil
}
Hi! We don't handle that possibility in this library because it either subprocess wsl.exe or run functions from the wslapi.dll, both require the parent process to be a console process otherwise they create a console for their own.
There is a quite involving alternative of creating a pseudoconsole to host the spawned process. One way to leverage that is writing your main application as a console application and having a Windows application (GUI subsystem) to create a pseudoconsole and host your main application. You control the pseudoconsole, its contents will only be displayed if you make the effort to do so. If you make your GUI invisible then everything will be invisible.