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.

Supersonic
  • 430
  • 1
  • 11
  • 35

2 Answers2

1

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)

Community
  • 1
  • 1
Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
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.

mr. Holiday
  • 1,780
  • 2
  • 19
  • 37