How to execute a powershell script?


#1

I am looking to execute a powershell script within a cookbook…

execute ‘test hello’ do
command 'c:\temp\hello.ps1’
action :run
end

It just opening up the file instead, how do I execute it?


#2

You want to use the powershell_script resource. See https://docs.chef.io/resource_powershell_script.html


#3

Thanks, that is showing how to execute an inline powershell script, I want to execute a remote powershell script ex…c:\temp\hello.ps1


#4

Hmm. The fact that c:\temp\hello.ps1 is in c:\ indicates it is local. Are you trying to run a local script on a separate remote node? Or maybe we are just mincing terms and you just want to run a script from disk inside of the chef run. I’ll go with that but correct me if I’m off.

I’d stick with the powershell_script resource and do something like:

powershell_script 'run remote script' do
    code '. c:\temp\hello.ps1'
end

This should simply “dot source” the script. If the code in the script is encapsulated inside of functions. Youd want to do:

powershell_script 'run remote script' do
  code <<-EOH
  . c:\temp\hello.ps1
  Invoke-MyFunction
  EOH
end

#6

Yes local script, but the following code doesn’t do any execution:

powershell_script 'run remote script' do
    code '. c:\temp\hello.ps1'
end


hello.ps1:
$text = 'Hello World'
$text >> 'file.txt'

run that locally and it works, missing something…


#7

hmmm. instead of 'file.txt' use an absolute path just to make sure its saving to where you expect.


#8

that worked!!! Thank you:smiley:


#9

i want to pass a variable $instance = #{node[‘t1’][‘message’]}.
i want it to pass through code property of powershell_script resource

can i do like this ???

powershell_script ‘run remote script’ do
code '. C:\t1\files\default\shell_cmd.ps1 “$instance”'
end