直接使用Puppet exec资源

时间:2017-03-01 12:17:23

标签: powershell puppet powershell-v3.0

我正在尝试使用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',
}

2 个答案:

答案 0 :(得分:1)

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

它提供了一个可用于执行Powershell命令的powershell提供程序。在木偶运行期间执行命令时,它可能会帮助你避免许多令人讨厌的边缘情况。

答案 1 :(得分:1)

正如@ arco444所建议的那样,我尝试在powershell命令中包装onlyif语句,它对我有用,但后来,正如我在帖子的更新部分所述,我又遇到了另一个问题。最后,以下工作:

$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',
}
相关问题