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

旧时模样 提交于 2019-12-08 12:17:55

问题


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


回答1:


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
 }


来源:https://stackoverflow.com/questions/40592641/how-to-set-powershell-executionpolicy-via-puppet-exec-command-with-unless-proper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!