ricardogaspar2
ricardogaspar2

Reputation: 51

How to set Powershell ExecutionPolicy via Puppet exec command with unless property on Windows?

I am using Puppet Enterprise version 3.8.6 to manage Windows servers. I am trying to make the setting of the Powershell Execution Policy idempodent. I tested several hypothesis, the last one is this:

# Setting Powershell Execution Policy to unrestricted
 exec { 'Set PowerShell execution policy unrestricted':
   command   => 'Set-ExecutionPolicy Unrestricted',
   unless    => 'if ((Get-ExecutionPolicy).ToString().Equals("Unrestricted")) { exit 0 } else { exit 1 }',
   provider  => powershell
 }

I already tested with double quotes and signle quotes, even escaping double quotes on Unrestricted word (e.g. \"Unrestricted\"). I also tested the command, but without success:

(Get-ExecutionPolicy).ToString(). -eq "Unrestricted"

It changes the ExecutionPolicy to Unrestricted, but in every Puppet run. It keeps falling in the else clause. The command works on Powershell. I would like it to be applied only when it's needed.

FYI: I already checked the Puppet documentation and searched onlne. some links I checked: http://glennsarti.github.io/blog/powershell-puppet-module-exit-codes/ https://docs.puppet.com/pe/latest/windows_config_mgmnt.html#executing-arbitrary-powershell-code

Upvotes: 1

Views: 593

Answers (1)

ferventcoder
ferventcoder

Reputation: 12551

I think this is due to how the PowerShell module calls PowerShell - it passes -ExecutionPolicy Bypass as part of the powershell.exe startup arguments, so local scope will always return Bypass, thus causing it to fail on the unless every time.

Try adding -Scope LocalMachine to your unless statement.

# Setting Powershell Execution Policy to unrestricted
 exec { 'Set PowerShell execution policy unrestricted':
   command   => 'Set-ExecutionPolicy Unrestricted',
   unless    => 'if ((Get-ExecutionPolicy -Scope LocalMachine).ToString() -eq "Unrestricted") { exit 0 } else { exit 1 }',
   provider  => powershell
 }

Upvotes: 1

Related Questions