B
B
bsbak2020-05-05 02:02:49
PowerShell
bsbak, 2020-05-05 02:02:49

How to run a console command with arguments?

I can’t figure out how to run a command (PowerShell) in linux from Go, I just run it in the console and everything works, and when from Go it displays a message as if I ran the command without arguments.

pwsh -Command 'Send-MailMessage -SMTPServer localhost -Port 25 -To [email protected] -From [email protected] -Subject "This is a test email" -Body "test body"
// в консоле отправляется нормально

from Go:
pwsh = "pwsh"
command = "-Command 'Send-MailMessage -SMTPServer localhost -Port 25 -To " + recipient + " -From " + user.Email + " -Subject \"" + subject + "\" -Body \"" + message + "\"'"
output, err := exec.Command(pwsh, command).Output()
//  результат: как будто просто написал pwsh
//  exit status 64
//  2020/05/05 01:33:48
//  Usage: pwsh[.exe] [-Login] 
 //                 [-Command { - | <script-block> [-args <arg-array>]
 //                               | <string> [<CommandParameters>] } ]
 //                 [-ConfigurationName <string>] [-CustomPipeName <string>]
//  ...

Tell me how to run from Go...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2020-05-05
@bsbak

command should be a slice of arguments, but yours is just a string
. You need it like this:

pwsh = "pwsh"
command = []string{"-Command", "Send-MailMessage -SMTPServer localhost -Port 25 -To " + recipient + " -From " + user.Email + ` -Subject "` + subject + `" -Body "` + message + `"`
output, err := exec.Command(pwsh, command...).Output()

I hope I understood the powershell syntax correctly, I think the basic principle is clear.
PS Use powershell in Linux, this monsieur, of course, knows a lot.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question