2017-03-01 31 views
0

我试图直接使用Puppet exec资源运行Powershell命令,而不是指定Powershell脚本的路径。直接使用Puppet exec资源运行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命令。但是,现在的问题是,如果我尝试检查不存在的 Win服务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 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', 
} 
+4

你可能还需要包装'onlyif'语句在PowerShell命令,我想现在它正在尝试运行一个可执行文件。 – arco444

+0

谢谢@ arco444!这工作。 :)你可以将它作为答案发布,我会关闭它。顺便说一句,有没有更好的选择,我可以雇用这个? – Technext

+0

再次卡住,虽然有不同的问题。更新了我的帖子。 – Technext

回答

1

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

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

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

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

+0

感谢您的建议。我实际上是所有的执行者使用powershell提供者,直到我面对[这](http://stackoverflow.com/questions/42484043/capturing-output-error-when-invoking-powershell-script/42485152?noredirect=1# comment72112698_42485152)问题。所以现在我正在避免它。 – Technext