5

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

sethvargo
  • 26,739
  • 10
  • 86
  • 156
user3140243
  • 103
  • 1
  • 4
  • I think this article answers your question. [1]: http://stackoverflow.com/questions/10286164/powershell-function-return-value – Jeremy Dec 27 '13 at 18:30
  • 2
    Thanks for your input here. My question is within Chef context and not in generic powershell terms. – user3140243 Dec 27 '13 at 18:34

2 Answers2

5

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 #=> ...
sethvargo
  • 26,739
  • 10
  • 86
  • 156
0

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