Complex PowerShell in Chef Recipe


#1

Hello!

New to Chef, so bare with me. I’ve written only a few recipes over the last few months. Come to my first real issue.

I have some complex PowerShell that we’ve used internally for quite sometime. This PowerShell does a lot of things (Server config, content deployments, windows features, DSC etc in one script) and I want to merge it into Chef. I’ve been trying for the last few hours to get If statements working in the PowerShell_Script resource. They don’t appear to work?

I’ve done some trial and error and I can’t get simple scripts like

powershell_script 'Install' do
code <<-EOH
   If ((Test-Path D:\Chef) -eq $True)
{
Do something
}
    EOH 

end

To work, is this just Chef way of saying you need to re-write?

I’ve also got functions that won’t compile into the recipe…

Rich


#2

Your code looks ok but you will need to double up on backslashes in paths when dropping code directly in to the code block. The EOH needs to not have any spaces after it, and you are missing an end from your block (I assume an oversight in the post). You end up with:

powershell_script 'Install' do
  code <<-EOH
    If ((Test-Path D:\\Chef) -eq $True)
    {
      # Do something
    }
    EOH
end

If you are migrating blocks of PowerShell code into Chef, you could take each block in isolation and use only_if to evaluate whether the block runs. This would look something like:

powershell_script 'Install' do
  code <<-EOH
    {
      # do the thing
    }
  EOH
  only_if "Test-Path D:\\Chef"
end

If you want to run a larger script of existing PowerShell you would probably want to “dot source” the script and then invoke the specific function, something like the following would help:

powershell_script 'Install' do
  code <<-EOH
  . c:\\dev\\repro\myscript.ps1
  Invoke-MyInstallFunction
  EOH
end

Hope that helps


#3

Thanks Stuart. I found the issue this morning to be syntax (about 10 minutes before I read this…- always the way)

Thanks for the comments about using only_if that feels more cheffy than what I was doing and it makes it much easier to read for the none windows engineers I am told!

Rich