2017-08-30 96 views
2

我正在編輯一個腳本,我需要將其轉換爲exe。它在運行時有幾個Write-Host腳本狀態的輸出。這導致腳本的exe文件顯示對話框給用戶,迫使他們在腳本完成前單擊OK 3或4次。隱藏寫主機輸出

我想保留Write-Host輸出,但只是當最終用戶從exe中執行它時隱藏它們(對話框)。

這可能嗎?我查看了代碼不喜歡的[void]。我可以開始工作的唯一方法就是用#發表評論,但我相信還有更好的辦法。

的我想要的實例隱藏/抑制:

Write-Host "Current Status = " $status 
+3

使用write-verbose。如果你使用param -verbose來壓縮腳本,這將會打印消息 – guiwhatsthat

回答

5

每應該使用Write-Verbose代替Write-Host,因爲這會給你你想要的功能用很少的努力的意見。但是使用Write-Verbose有一對夫婦的其他變化,你需要做:

首先,您需要把它添加到你的腳本的頂部:

[cmdletbinding()] 
Param() 

這使你的腳本一組默認參數之一包括-Verbose,它可以在使用時顯示任何Write-Verbose消息。其次(根據您提供的示例),您可能需要稍微重寫一些(現在的)Write-Verbose字符串語句。例如:

write-host "Current Status = " $status 

作品與Write-Host,因爲它需要字符串作爲輸入的陣列。這同樣不是真正Write-Verbose,只需要一個字符串,那麼上面的例子就需要被改爲:

Write-Verbose "Current Status = $status" 

請注意,使用雙引號字符串變量仍然會擴大。

0

你可以試試這個:

function Remove-WriteHost 
{ 
    [CmdletBinding(DefaultParameterSetName = 'FromPipeline')] 
    param(
    [Parameter(ValueFromPipeline = $true, ParameterSetName = 'FromPipeline')] 
    [object] $InputObject, 

    [Parameter(Mandatory = $true, ParameterSetName = 'FromScriptblock', Position = 0)] 
    [ScriptBlock] $ScriptBlock 
    ) 

    begin 
    { 
    function Cleanup 
    { 
     # clear out our proxy version of write-host 
     remove-item function:\write-host -ea 0 
    } 

    function ReplaceWriteHost([string] $Scope) 
    { 
     Invoke-Expression "function ${scope}:Write-Host { }" 
    } 

    Cleanup 

    # if we are running at the end of a pipeline, need to immediately inject our version 
    # into global scope, so that everybody else in the pipeline uses it. 
    # This works great, but dangerous if we don't clean up properly. 
    if($pscmdlet.ParameterSetName -eq 'FromPipeline') 
    { 
     ReplaceWriteHost -Scope 'global' 
    } 
    } 
} 
Remove-WriteHost 

現在試試:

Write-Host "Something" 

輸出將一無所獲。

請參考:THIS