调用 PowerShell 脚本时捕获 output/error

Capturing output/error when invoking PowerShell script

我正在尝试从 Puppet 调用 PowerShell 脚本。问题是即使 PowerShell 脚本在远程框上失败,它仍然显示成功 运行,如下所示:

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

我在 site.pp 中的节点块的内容:

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

当我从 PowerShell 控制台尝试 运行ning 时脚本失败,表明执行策略设置为受限。

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

从 Puppet 调用脚本时如何捕获上述错误以避免以后出现意外?

您需要设置退出代码以使 Puppet 拾取失败:

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

但是,自从 powershell provider should normally execution policies, the error you observed means that the execution policy is enforced via group policy.

更好的方法是修复您环境中的执行策略,这样它就不会禁止脚本执行,并让您的脚本 return 有一个退出代码来指示是否启用了 UAC。

如果由于某些不明确的原因您无法解决实际问题而不得不处理症状,您需要直接 exec PowerShell,如下所示:

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',
}

powershell 提供程序在这种情况下不起作用。


如果您只想确定 PowerShell 脚本的执行是否受到限制,我认为动态事实是确定该信息的更好方法,例如在 %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
)