Windows PowerShell support

Posted by Mahesh Kumar
May 24, 2013

Recently support for Windows PowerShell was merged into the Enterprise Windows version of CFEngine. PowerShell is Microsoft’s enhanced shell, intended for more advanced system administration and programming tasks.

The change to CFEngine means you can seamlessly use PowerShell in your configuration policies, just like the normal “cmd” shell. It’s very easy, for example, say you have the following bundle:

bundle agent mybundle
{
  vars:
    "mymessage"
      string => execresult("echo This is a message from cmd", "useshell");

  reports:
    "$(mymessage)";
}

This uses the regular “cmd” shell. To switch to PowerShell, just replace it with the following:

bundle agent mybundle
{
  vars:
    "mymessage"
      string => execresult("Write-Output This is a message from PowerShell", "powershell");

  reports:
    "$(mymessage)";
}

You can also use the powershell class to detect whether PowerShell is available:

bundle agent mybundle
{
  vars:
    powershell::
      "mymessage"
        string => execresult("Write-Output This is a message from PowerShell", "powershell");

    !powershell::
      "mymessage"
        string => execresult("echo This is a message from cmd", "useshell");

  reports:
    "$(mymessage)";
}

You can use PowerShell in the two functions “execresult()” and “returnszero()”, as well as in the “commands” promise type. To use it in the “commands” promise type, use the “useshell” attribute in the “contain” body of a “commands” promise:

bundle agent mybundle
{
  commands:
    "Write-Output Hello world"
      contain => mycontainbody;
}

body contain mycontainbody
{
  useshell => "powershell";
}

In relation to PowerShell support, a number of changes was also made to the non-Windows shell handling, both in the Enterprise and Community version of CFEngine:

  • Commands executed using “useshell” no longer requires the first word to be an absolute path. This was originally in place for security reasons, but in a complex shell expression this security measure does not work, and was therefore removed entirely. Absolute path names are still required for the “noshell” type, which is recommended whenever possible.
  • The “useshell” attribute inside the “contain” body used to take boolean values. Now it takes one of the following values: “noshell”, “useshell” or “powershell”.

PowerShell support will be available in CFEngine version 3.5.0.