Capturing output/error when invoking PowerShell script

自作多情 提交于 2019-11-28 02:17:11

问题


I am trying to invoke a PowerShell script from Puppet. The issue is even if the PowerShell script fails on remote box, it still shows successful run as shown below:

Notice: /Stage[main]/Main/Node[dev.abc.com]/Exec[Check UAC]/returns: executed successfully

Content of my node block in site.pp:

exec { 'Check UAC':
  command   => '& C:\temp\check_uac.ps1',
  provider  => powershell,
  logoutput => 'on_failure',
}

The script failed when I tried running from PowerShell console stating that execution policy was set to Restricted.

PS C:\> C:\temp\check_uac.ps1
C:\temp\check_uac.ps1 : File C:\temp\check_uac.ps1 cannot be loaded because running
scripts is disabled on this system. For more information, see about_Execution_Policies
at http://go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ C:\temp\check_uac.ps1
+ ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : SecurityError: (:) [], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess

How can I capture the above error when invoking the script from Puppet to avoid surprises later?


回答1:


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
)


来源:https://stackoverflow.com/questions/42484043/capturing-output-error-when-invoking-powershell-script

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