3

I would like to achieve this using win32ole only and not any other way to execute shell commands in ruby.

require 'win32ole'
shell = WIN32OLE.new('Shell.Application')
my_username = shell.ShellExecute('cmd.exe', 'username', '', 'open', 0)
puts my_username

#Current output => nil

Just want to print my username but generally would like to execute any commands and get its output. I know we have ENV['user'] or echo %username% gives me what I want but want this using win32ole only.

Thanks a lot in advance.

6
  • The second parameter to ShellExecute is Directory and username in your case is nothing that's why you get nil output Commented Sep 3, 2015 at 13:25
  • @IliaAptsiauri: Tried out different ways, but still not able to get it to work. Can you please help Commented Sep 4, 2015 at 5:48
  • @IliaAptsiauri: directory is the third parameter, no? msdn.microsoft.com/en-us/library/windows/desktop/… Commented Sep 4, 2015 at 7:02
  • @SergioTulentsev thanks for noticing you are correct Commented Sep 4, 2015 at 7:16
  • Does cmd.exe even accept commands as parameters this way? Commented Sep 7, 2015 at 12:25

2 Answers 2

1
+50

You should try with whoami instead of username:

require 'win32ole'
shell = WIN32OLE.new('Shell.Application')
my_username = shell.ShellExecute('cmd.exe', 'whoami', '', 'open', 0)
puts my_username


You can't use ShellExecute() because it doesn't let you access the output of the command your run which is what you want. See Using ShellExecuteEx and capturing standard in/out/err for more informations about that point.

I would simply use puts ENV['USERNAME'] which works like a charm. (Or any command given by Ilia Aptsiauri in his answer)

Sign up to request clarification or add additional context in comments.

Comments

0

If you just want to execute Windows CLI commands you need to take little bit different approach. Instead of whoami you can put any command you want

  • system("whoami")
  • `whoami` (these are backticks)
  • spawn("whoami")

The difference between those are the following

  • system waits until "The command" has finished and outputs everything to $stdout. Then it returns true or false depending on the exitstatus.
  • The backticks wait as well, but return the output made by the program.
  • spawn doesn't wait, but rather returns the PID of the subprocess. Note that this requires Ruby 1.9 on Windows to work.

There is one more option check Open3 library it get's little bit more information during the output.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.