Excute windows cmd in ruby

hi all,
im new to ruby, I try to run windows cmd in ruby but without any success.

I try until now:

command = 'C:\\create_folder.cmd'
`#{command}`
require 'open3'

Open3.popen3("C:\\Windows\\System32\\cmd.exe","/c", "C:\\create_folder.cmd") do |stdin, stdout, stderr, thread|
   pid = thread.pid
   puts stdout.read.chomp
end

system("C:\\Windows\\System32\\cmd.exe", "C:\\create_folder.cmd")
create_directory = %x('C:\\create_folder.bat')

Does anyone know why those doesnt work? or any ideas ?

thank you all

1 Like

watch this video - YouTube
I think in it help you find out more about Execute windows command in ruby

1 Like

You did not specify, which Ruby version you are using. At least for the first argument of popen3 or system, I would use forward slashes as path separators (at least this is necessary in the Cygwin port of Ruby which I am using). In any case, explicitly specifying cmd.exe makes sense to me, unless it is a Ruby implementation written explicitly for the Windows platform (and even in this case, I think that COMSPEC needs to be set to tell Ruby which shell interpreter to use).

Of course for the other parameters to cmd.exe, it’s better to provid backslashes as path separator, because cmd.exe, AFIK, can’t deal with forward slashes.

To run Windows command prompt (CMD) commands within Ruby, you can use the system method or backticks (`) to execute the command. Here’s an example:

Using the system method

system(‘command_to_execute’)

Using backticks

result = command_to_execute

Printing the result

puts result

In the above code, replace 'command_to_execute' with the actual command you want to run in the Windows CMD. For example, if you want to run the dir command to list the files in the current directory, you can do the following:

system(‘dir’)