user3140243
user3140243

Reputation: 103

Chef - Returning a variable from powershell script

I would like to know if there is a way to return a variable value from a powershell script defined in powershell_script resource?

My powershell resource looks like following:

powershell_script "Test Script" do
  code <<-EOH
    Write-Host "Hello World!"
   return "test"
  EOH
end

I would like to use the returned value test from the script to use in other resources based on if conditions.

Thanks

Upvotes: 5

Views: 5647

Answers (2)

brendonmartino
brendonmartino

Reputation: 51

We actually came across this exact issue and solved it by writing our own Mixlib to get the exit code from a powershell script. Example:

# get the result object (and exit code) from the code execution:           
result = Mixlibrary::Core::Shell.windows_script_out(:powershell, mycode)
exit_status = result.exitstatus

@carpNick is planning on open-sourcing this perhaps as soon as this week....at the moment it only handles powershell, but we plan on implementing support for other types as well (bash, win modules, etc.) -- which should be fairly easy to add on support for others.

We are currently using it in-house and it works great. I'm sure Chef will want to review Nick's excellent code once he gets it out there. We are just waiting on legal to tell us what open-source license to use.

Ask Nick for more details... @carpnick | https://github.com/carpnick

Upvotes: 0

sethvargo
sethvargo

Reputation: 26997

Ohai!

I think you actually want to use the PowershellOut Mixin found here in the Powershell cookbook.

Chef resources rarely return values, but that's what heavy-weight resources are for!

If you have the powershell cookbook, you can do this:

include Chef::Mixin::PowershellOut
cmd = powershell_out!('command')
cmd.stdout #=> ...
cmd.stderr #=> ...

Upvotes: 5

Related Questions