Chef and PowerShell condition

Hi all,

I’m not sure if this Chef/ruby, PowerShell or me missing something obvious but any help would be appreciated :slight_smile:

I want to block code being run if the version of a file is newer than the one expected.

ruby ‘example_code’ do
code <<-EOH
sleep 10
EOH
guard_interpreter :powershell_script
not_if '
& $installed_version = (Get-Item E:/Apps/application.exe).VersionInfo.FileVersion
& $installed_version = $installed_version.substring(0,4)
& $installed_version -replace “,”,"."
& $installed_version < “2”
'
end

If I run the first 3 PowerShell lines natively on the app server it returns the version of application.exe as 1.23.

Why then would the Chef code block execute everytime as not_if 1.23 is less than 2

I hope that makes sense. I tried single quotes / double quotes around the 2 no difference.

Any help appreciated.

Dave

I think you are trying to perform a less than check on strings instead of integers. I would convert your $installed_version to integer, and drop the quotes around 2.

This line is not an integer compare

$installed_version < "2"

It throws error

"The '<' operator is reserved for future use

Try something like this

    $installed_version -lt "2"

A full example:

ruby 'example_code' do
  code <<-EOH
    sleep 10
  EOH
  guard_interpreter :powershell_script
  convert_boolean_return true
  not_if {
    $installed_version = (Get-Item E:/Apps/application.exe).VersionInfo.FileVersion;
    $installed_version = $installed_version.substring(0,4);
    $installed_version -replace ",",".";
    $installed_version -lt "2"
  }
end

A few other suggestions:

  • Use real quotes " not curly quotes “
  • probably don’t need to prepend each command with &
  • The not_if interpreters don’t run at the same time as the ruby block, so realize it is possible for race conditions

Hi donwlewis and spuder - thank you both for your helpful responses.

Converting the string to integer ensured the only_if / not_if was successful so thats great.

I’ll also read up on the race conditions to understand potential impact on that.

Cheers

Dave