2017-03-01 30 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