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

2
  • I think this article answers your question. [1]: stackoverflow.com/questions/10286164/… Commented Dec 27, 2013 at 18:30
  • 2
    Thanks for your input here. My question is within Chef context and not in generic powershell terms. Commented Dec 27, 2013 at 18:34

2 Answers 2

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 #=> ...
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks! I ended up using that. Do you know if PowershellOut is included in windows cookbook by default in version 11.8.x?
Thanks! Your response is much appreciated.
This is actually a lesser-known feature of the PS cookbook and could really benefit from a blog post. Would you like to write one?
I have added a blog posting here kapilshardha.blogspot.com/2013/12/… Let me know if you have any suggestions on improving it.
@sethvargo Your referenced link is broken.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.