class WinrmClass

Wrapper class to interact with winrm

Public Instance Methods

winrm_run(script, host, user = nil , password = nil) click to toggle source
# File lib/miq_utilities/winrm.rb, line 15
  def winrm_run(script, host, user = nil , password = nil)
    @logger = LoggingClass.new('WinRM')
    user ||= 'administrator'
    password ||= $evm.object.decrypt('win_password').to_s
    value = ''
    ps1 = <<~PS_SCRIPT
      #{script}
    PS_SCRIPT

    opts = {
      endpoint: "http://#{host}:5985/wsman",
      user: user.to_s,
      password: password.to_s
    }

    conn = WinRM::Connection.new(opts)

    @logger.log(level: 'info', message: "WinRM is connecting to #{opts[:endpoint]}")
    msg = ps1.to_s.gsub(password.to_s, '****')
    @logger.log(level: 'info', message: "Running PowerShell script: #{msg}")

    conn.shell(:powershell) do |shell|
      err = ''
      output = shell.run(ps1) do |stdout, stderr|
        value = stdout
        err = stderr
      end
      if output.exitcode.zero?
        @logger.log(level: 'info', message: "PS script finished with exit code #{output.exitcode} - Output: <#{value.to_s.strip}>")
      else
        @logger.log(level: 'error', message: "PS script failed with exit code #{output.exitcode} and error message #{err}. STDOUT: #{value.to_s.strip}")
      end
    end
    value.to_s.strip
  end