Capturing output/error when invoking PowerShell script

筅森魡賤 提交于 2019-11-29 08:48:52
Ansgar Wiechers

You need to set an exit code to have Puppet pick up failures:

exec { 'Check UAC':
  command   => '& C:\temp\check_uac.ps1; exit (1 - [int]$?)',
  provider  => powershell,
  logoutput => 'on_failure',
}

However, since the powershell provider should normally bypass execution policies, the error you observed means that the execution policy is enforced via group policy.

A better approach would be to fix the execution policy in your environment, so that it doesn't prohibit script execution, and have your script return an exit code to indicate whether or not UAC is enabled.

If for some obscure reason you cannot fix the actual problem and have to deal with the symptoms instead, you need to exec PowerShell directly, like this:

exec { 'Check UAC':
  command   => 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -NoProfile -NoLogo -NonInteractive -Command "& {C:\temp\check_uac.ps1; exit (1 - [int]$?)}"',
  logoutput => 'on_failure',
}

The powershell provider won't work in this scenario.


If all you want is to determine whether or not execution of PowerShell scripts is restricted, I would consider a dynamic fact a better way to determine that information, e.g. with a batch script in %AllUsersProfile%\PuppetLabs\facter\facts.d:

@echo off

for /f "tokens=* delims=" %%p in (
  'powershell -NoProfile -NonInteractive -NoLogo -Command "Get-ExecutionPolicy"'
) do set "policy=%%p"

if /i "%policy%"=="restricted" (
  echo ExecutionRestricted=true
) else (
  echo ExecutionRestricted=false
)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!