Class: Vagrant::Util::PowerShell

Inherits:
Object
  • Object
show all
Defined in:
lib/vagrant/util/powershell.rb

Overview

Executes PowerShell scripts.

This is primarily a convenience wrapper around Subprocess that properly sets powershell flags for you.

Constant Summary collapse

MINIMUM_REQUIRED_VERSION =

NOTE: Version checks are only on Major

3
DEFAULT_VERSION_DETECTION_TIMEOUT =

Number of seconds to wait while attempting to get powershell version

30
LOGGER =
Log4r::Logger.new("vagrant::util::powershell")

Class Method Summary collapse

Class Method Details

.available?Boolean

Returns powershell executable available on PATH.

Returns:

  • (Boolean)

    powershell executable available on PATH



46
47
48
# File 'lib/vagrant/util/powershell.rb', line 46

def self.available?
  !executable.nil?
end

.executableString|nil

Returns a powershell executable, depending on environment.

Returns:

  • (String|nil)

    a powershell executable, depending on environment



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/vagrant/util/powershell.rb', line 20

def self.executable
  if !defined?(@_powershell_executable)
    @_powershell_executable = "powershell"

    if Which.which(@_powershell_executable).nil?
      # Try to use WSL interoperability if PowerShell is not symlinked to
      # the container.
      if Platform.wsl?
        @_powershell_executable += ".exe"

        if Which.which(@_powershell_executable).nil?
          @_powershell_executable = "/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe"

          if Which.which(@_powershell_executable).nil?
            @_powershell_executable = nil
          end
        end
      else
        @_powershell_executable = nil
      end
    end
  end
  @_powershell_executable
end

.execute(path, *args, **opts, &block) ⇒ Subprocess::Result

Execute a powershell script.

Parameters:

  • path (String)

    Path to the PowerShell script to execute.

  • args (Array<String>)

    Command arguments

  • opts (Hash)

    Options passed to execute

Options Hash (**opts):

  • :env (Hash)

    Custom environment variables

Returns:



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/vagrant/util/powershell.rb', line 57

def self.execute(path, *args, **opts, &block)
  validate_install!
  if opts.delete(:sudo) || opts.delete(:runas)
    powerup_command(path, args, opts)
  else
    if mpath = opts.delete(:module_path)
      m_env = opts.fetch(:env, {})
      m_env["PSModulePath"] = "$env:PSModulePath+';#{mpath}'"
      opts[:env] = m_env
    end
    if env = opts.delete(:env)
      env = env.map{|k,v| "$env:#{k}=#{v}"}.join(";") + "; "
    end
    command = [
      executable,
      "-NoLogo",
      "-NoProfile",
      "-NonInteractive",
      "-ExecutionPolicy", "Bypass",
      "#{env}&('#{path}')",
      args
    ].flatten

    # Append on the options hash since Subprocess doesn't use
    # Ruby 2.0 style options yet.
    command << opts

    Subprocess.execute(*command, &block)
  end
end

.execute_cmd(command, **opts) ⇒ nil, String

Execute a powershell command.

Parameters:

  • command (String)

    PowerShell command to execute.

  • opts (Hash)

    Extra options

Options Hash (**opts):

  • :env (Hash)

    Custom environment variables

Returns:

  • (nil, String)

    Returns nil if exit code is non-zero. Returns stdout string if exit code is zero.



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/vagrant/util/powershell.rb', line 95

def self.execute_cmd(command, **opts)
  validate_install!
  if mpath = opts.delete(:module_path)
    m_env = opts.fetch(:env, {})
    m_env["PSModulePath"] = "$env:PSModulePath+';#{mpath}'"
    opts[:env] = m_env
  end
  if env = opts.delete(:env)
    env = env.map{|k,v| "$env:#{k}=#{v}"}.join(";") + "; "
  end
  c = [
    executable,
    "-NoLogo",
    "-NoProfile",
    "-NonInteractive",
    "-ExecutionPolicy", "Bypass",
    "-Command",
    "#{env}#{command}"
  ].flatten.compact

  r = Subprocess.execute(*c)
  return nil if r.exit_code != 0
  return r.stdout.chomp
end

.execute_inline(*command, **opts, &block) ⇒ Object

Execute a powershell command and return a result

Parameters:

  • command (String)

    PowerShell command to execute.

  • opts (Hash)

    A collection of options for subprocess::execute

  • block (Block)

    Ruby block

Options Hash (**opts):

  • :env (Hash)

    Custom environment variables



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/vagrant/util/powershell.rb', line 126

def self.execute_inline(*command, **opts, &block)
  validate_install!
  if mpath = opts.delete(:module_path)
    m_env = opts.fetch(:env, {})
    m_env["PSModulePath"] = "$env:PSModulePath+';#{mpath}'"
    opts[:env] = m_env
  end
  if env = opts.delete(:env)
    env = env.map{|k,v| "$env:#{k}=#{v}"}.join(";") + "; "
  end

  command = command.join(' ')

  c = [
    executable,
    "-NoLogo",
    "-NoProfile",
    "-NonInteractive",
    "-ExecutionPolicy", "Bypass",
    "-Command",
    "#{env}#{command}"
  ].flatten.compact
  c << opts

  Subprocess.execute(*c, &block)
end

.powerup_command(path, args, opts) ⇒ Array<String>

Powerup the given command to perform privileged operations.

Parameters:

  • path (String)
  • args (Array<String>)

Returns:

  • (Array<String>)


210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
# File 'lib/vagrant/util/powershell.rb', line 210

def self.powerup_command(path, args, opts)
  Dir.mktmpdir("vagrant") do |dpath|
    all_args = [path] + args.flatten.map{ |a|
      a.gsub(/^['"](.+)['"]$/, "\\1")
    }
    arg_list = "\"" + all_args.join("\" \"") + "\""
    stdout = File.join(dpath, "stdout.txt")
    stderr = File.join(dpath, "stderr.txt")

    script = "& #{arg_list} ; exit $LASTEXITCODE;"
    script_content = Base64.strict_encode64(script.encode("UTF-16LE", "UTF-8"))

    # Wrap so we can redirect output to read later
    wrapper = "$p = Start-Process -FilePath powershell -ArgumentList @('-NoLogo', '-NoProfile', " \
      "'-NonInteractive', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', '#{script_content}') " \
      "-PassThru -WindowStyle Hidden -Wait -RedirectStandardOutput '#{stdout}' -RedirectStandardError '#{stderr}'; " \
      "if($p){ exit $p.ExitCode; }else{ exit 1 }"
    wrapper_content = Base64.strict_encode64(wrapper.encode("UTF-16LE", "UTF-8"))

    powerup = "$p = Start-Process -FilePath powershell -ArgumentList @('-NoLogo', '-NoProfile', " \
      "'-NonInteractive', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', '#{wrapper_content}') " \
      "-PassThru -WindowStyle Hidden -Wait -Verb RunAs; if($p){ exit $p.ExitCode; }else{ exit 1 }"

    cmd = [
      "powershell",
      "-NoLogo",
      "-NoProfile",
      "-NonInteractive",
      "-ExecutionPolicy", "Bypass",
      "-Command", powerup
    ]

    result = Subprocess.execute(*cmd.push(opts))
    r_stdout = result.stdout
    if File.exist?(stdout)
      r_stdout += File.read(stdout)
    end
    r_stderr = result.stderr
    if File.exist?(stderr)
      r_stderr += File.read(stderr)
    end

    Subprocess::Result.new(result.exit_code, r_stdout, r_stderr)
  end
end

.reset!Object

Reset the cached values for platform. This is not considered a public API and should only be used for testing.



259
260
261
# File 'lib/vagrant/util/powershell.rb', line 259

def self.reset!
  instance_variables.each(&method(:remove_instance_variable))
end

.validate_install!Boolean

Validates that powershell is installed, available, and at or above minimum required version

Returns:

  • (Boolean)


192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/vagrant/util/powershell.rb', line 192

def self.validate_install!
  if !defined?(@_powershell_validation)
    raise Errors::PowerShellNotFound if !available?
    if version.to_i < MINIMUM_REQUIRED_VERSION
      raise Errors::PowerShellInvalidVersion,
        minimum_version: MINIMUM_REQUIRED_VERSION,
        installed_version: version ? version : "N/A"
    end
    @_powershell_validation = true
  end
  @_powershell_validation
end

.versionString

Returns the version of PowerShell that is installed.

Returns:

  • (String)


156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/vagrant/util/powershell.rb', line 156

def self.version
  if !defined?(@_powershell_version)
    command = [
      executable,
      "-NoLogo",
      "-NoProfile",
      "-NonInteractive",
      "-ExecutionPolicy", "Bypass",
      "-Command",
      "Write-Output $PSVersionTable.PSVersion.Major"
    ].flatten

    version = nil
    timeout = ENV["VAGRANT_POWERSHELL_VERSION_DETECTION_TIMEOUT"].to_i
    if timeout < 1
      timeout = DEFAULT_VERSION_DETECTION_TIMEOUT
    end
    begin
      r = Subprocess.execute(*command,
        notify: [:stdout, :stderr],
        timeout: timeout,
      ) {|io_name,data| version = data}
    rescue Vagrant::Util::Subprocess::TimeoutExceeded
      LOGGER.debug("Timeout exceeded while attempting to determine version of Powershell.")
    end

    @_powershell_version = version
  end
  @_powershell_version
end