Method: Inspec::Resources::WindowsPkg#info

Defined in:
lib/resources/package.rb

#info(package_name) ⇒ Object



258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# File 'lib/resources/package.rb', line 258

def info(package_name)
  search_paths = [
    'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*',
    'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*',
  ]

  # add 64 bit search paths
  if inspec.os.arch == 'x86_64'
    search_paths << 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'
    search_paths << 'HKCU:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'
  end

  # Find the package
  cmd = inspec.command <<-EOF.gsub(/^\s*/, '')
    Get-ItemProperty (@("#{search_paths.join('", "')}") | Where-Object { Test-Path $_ }) |
    Where-Object { $_.DisplayName -like "#{package_name}" -or $_.PSChildName -like "#{package_name}" } |
    Select-Object -Property DisplayName,DisplayVersion | ConvertTo-Json
  EOF

  # We cannot rely on `exit_status` since PowerShell always exits 0 from the
  # above command. Instead, if no package is found the output of the command
  # will be `''` so we can use that to return `{}` to match the behavior of
  # other package managers.
  return {} if cmd.stdout == ''

  begin
    package = JSON.parse(cmd.stdout)
  rescue JSON::ParserError => e
    raise Inspec::Exceptions::ResourceFailed,
          'Failed to parse JSON from PowerShell. ' \
          "Error: #{e}"
  end

  # What if we match multiple packages?  just pick the first one for now.
  package = package[0] if package.is_a?(Array)

  {
    name: package['DisplayName'],
    installed: true,
    version: package['DisplayVersion'],
    type: 'windows',
  }
end