Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execute powershell commands from ruby

I was trying to execute a powershell command from ruby code. Get-WmiObject -Class Win32_Product -ComputerName . -Filter "Name='Qlik Sense Client'" |Select-Object -Property version

It gives me the version of the product perefectly. But the same thing when i try to execute from ruby like(entire command in backticks) : find = powershell.exe Get-WmiObject -Class Win32_Product -ComputerName . -Filter "Name=''"|Select-Object -Property version

The command breaks, it cant interpret the quotes, pipes etc in ruby. I tried to escape those quotes but it still it breaks. I dont know how to escape that pipe as well. Kindly help me here or refer me to something relevant. Many thanks.

like image 654
padmaksha roy Avatar asked Dec 04 '17 14:12

padmaksha roy


1 Answers

I have tested this now:

require 'base64'
cmd = %{Get-WmiObject -Class Win32_Product -ComputerName . -Filter "Name='Qlik Sense Client'"|Select-Object -Property version}
encoded_cmd = Base64.strict_encode64(cmd.encode('utf-16le'))
find = `powershell.exe -encodedCommand #{encoded_cmd}`

Powershell expects UTF-16LE-encoded strings, so you have to convert from Ruby's encoding (UTF-8) before the base64 conversion.


Alternatively you could try using shellescape from shellwords to escape the command so the shell interprets it as a single string.

Another alternative is to use powershell.exe -Command - with popen3. That will let you write your commands and read their results using a file stream.

like image 167
Max Avatar answered Oct 10 '22 15:10

Max