运行 直接使用 Puppet exec 资源的 Powershell 命令

Running Powershell command directly using Puppet exec resource

我正在尝试 运行 直接使用 Puppet exec 资源而不是指定 Powershell 脚本路径的 Powershell 命令。

exec { "Change status and start-up of Win service":
    command => 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -NoLogo -NonInteractive -Command "& {set-service Spooler -Status Running -StartupType Automatic; exit (1 - [int]$?)}"',
    onlyif  => "if(Get-Service Spooler) { exit 0 } else { exit 1 }",
    logoutput => 'on_failure',
}

当我尝试 运行 执行上述命令时,出现以下错误:

Error: Failed to apply catalog: Parameter onlyif failed on Exec[Change status and start-up of Win service]: 'if(Get-Service Spooler
) { exit 0 } else { exit 1 }' is not qualified and no path was specified. Please qualify the command or specify a path. at /etc/puppetlabs/code/environments/production/modules/common/manifests/svc_auto_running.pp:17

看到几个链接,所有链接都提到了指定二进制文件的完整路径,在这种情况下,我认为 是 PS 可执行文件的路径,并且已经指定。

我们将不胜感激。

更新:在我尝试在 powershell 命令中包装 onlyif 语句后,我能够直接使用 exec 成功 运行 powershell 命令。但是,现在的问题是,如果我尝试在 onlyif 语句中检查 不存在的 Win 服务,命令 仍然成功通过 .

$powershell = 'C:/Windows/System32/WindowsPowerShell/v1.0/powershell.exe -NoProfile -NoLogo -NonInteractive'

exec { "Change status and start-up of Win service":
    command   => "$powershell -Command '& {set-service iDoNotExist -Status Running -StartupType Automatic; exit (1 - [int]$?)}'",
    #onlyif   => "$powershell -Command '& {if(Get-Service iDoNotExist); exit (1 - [int]$?)}'",
    onlyif    => "$powershell -Command '& {if(Get-Service iDoNotExist) { exit 0 } else { exit 1 }}'",
    logoutput => 'on_failure',
}

可能最好使用 powershell privider 来 运行 这些命令。您可以安装此模块:puppetlabs/powershell

它提供了一个可用于执行 Powershell 命令的 powershell 提供程序。在 puppet 运行.

期间执行命令时,它可能会帮助您避免很多讨厌的边缘情况

按照@arco444 的建议,我尝试将 onlyif 语句包装在 powershell 命令中,它对我有用,但后来,如我的 post 的更新部分所述,我得到了另一个问题。最后,以下工作:

$powershell = 'C:/Windows/System32/WindowsPowerShell/v1.0/powershell.exe -NoProfile -NoLogo -NonInteractive'

exec { "Change status and start-up of Win service":
    command   => "$powershell -Command \"& {set-service $service_name -Status Running -StartupType Automatic; exit (1 - [int]$?)}\"",
    onlyif    => "$powershell -Command '& {\"if(Get-Service ${service_name})\"; exit (1 - [int]$?)}'",
    logoutput => 'on_failure',
}