Module: Specinfra::Backend::PowerShell::ScriptHelper

Included in:
Cmd, Winrm
Defined in:
lib/specinfra/backend/powershell/script_helper.rb

Instance Method Summary collapse

Instance Method Details

#add_pre_command(cmd) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/specinfra/backend/powershell/script_helper.rb', line 20

def add_pre_command(cmd)
  path = get_config(:path)
  if get_config(:pre_command)
    cmd.strip!
    cmd =
<<-EOF
#{get_config(:pre_command)}
#{cmd}
EOF
    cmd = "$env:path = \"#{path};$env:path\"\n#{cmd}" if path
  end
  cmd
end

#build_command(cmd) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/specinfra/backend/powershell/script_helper.rb', line 7

def build_command(cmd)
  path = get_config(:path)
  if path
    cmd.strip!
    cmd =
<<-EOF
$env:path = "#{path};$env:path"
#{cmd}
EOF
  end
  cmd
end

#check_running(process) ⇒ Object



71
72
73
74
75
76
77
78
79
80
# File 'lib/specinfra/backend/powershell/script_helper.rb', line 71

def check_running(process)
  ret = run_command(commands.check_running(process))

  # If the service is not registered, check the process
  if ret.exit_status == 1
    ret = run_command(commands.check_process(process))
  end

  ret.success?
end

#create_script(command) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/specinfra/backend/powershell/script_helper.rb', line 47

def create_script command
  if command.is_a? Command
    ps_functions = command.import_functions.map { |f| File.read(File.join(File.dirname(__FILE__), 'support', f)) }
    script = build_command(command.script)
    script = add_pre_command(script)
    <<-EOF
$exitCode = 1
$ProgressPreference = "SilentlyContinue"
try {
  #{ps_functions.join("\n")}
  $success = $(#{script})
  if ($success -is [Boolean] -and $success) { $exitCode = 0 }
} catch {
  Write-Output $_.Exception.Message
}
Write-Output "Exiting with code: $exitCode"
exit $exitCode
  EOF
  else
    script = build_command(command.to_s)
    add_pre_command(script)
  end
end

#encode_script(script) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/specinfra/backend/powershell/script_helper.rb', line 34

def encode_script script
  script_text = script.chars.to_a.join("\x00").chomp
  script_text << "\x00" unless script_text[-1].eql? "\x00"
  if script_text.respond_to?(:encode)
    script_text = script_text.encode('ASCII-8BIT')
  end
  if Base64.respond_to?(:strict_encode64)
    Base64.strict_encode64(script_text)
  else
    [ script_text ].pack("m").strip
  end
end