2012-01-24 30 views
7

我有一個PS腳本:如何抑制PowerShell中獲取內容輸出

script.ps1

[System.Xml.XmlDocument] $Config; 

function Get-ScriptDirectory 
{ 
    Split-Path $script:MyInvocation.MyCommand.Path 
} 

function Load-Config 
{ 
    $configPath = Join-Path (Get-ScriptDirectory) config.xml 
    $global:Config = [xml](gc $configPath) 
} 

Load-Config 

config.xml中

<Configuration> 
</Configuration> 

在我的工作劇本後來$配置變量。當我運行這個腳本時,它將輸出寫入到包含xml根元素的控制檯。例如:

Configuration 
-------------- 

是否存在任何方式如何抑制此輸出?

謝謝。

回答

6

可能輸出不被賦值語句(一個可撤銷的聲明)造成的,而是由這條線:

[System.Xml.XmlDocument] $Config;

在PowerShell中,通常,所有語句都會返回一個值(除了可以使用的語句)。我認爲你第一次運行這個腳本沒有輸出會被寫入控制檯。但是,在後續運行$Config仍將包含上一次運行的值,並將其值寫入屏幕。

  • 管道到出空的cmdlet: [System.Xml.XmlDocument] $Config | Out-Null
  • 鑄造到void: [void][System.Xml.XmlDocument]$Config
  • 指定爲$ null: $null = $Config
  • 或根本就沒有 '聲明' 的$Config變量

是抑制此行爲的方法。

0

某處您從腳本中傾銷變量。當它脫離管道時,它會傳遞給Out-Host,並且會產生你看到的輸出。

實際的解決方案是確保您不會從腳本中返回任何內容。由於我看不到你的代碼,我不能指向哪裏,但在某處存在將對象泄漏到輸出中的管道或語句。你確定你在每個需要的地方使用作業嗎?

4

如果你不想被打印到控制檯命令的輸出,則可以通過管道重定向Out-Null丟棄它。例如既會工作:

$Config | Out-Null 
$Config > Out-Null 

如果你熟悉的類Unix操作系統,Out-Null相當於/dev/null概念。

+0

您也可以分配給'$ null'。在任何情況下,它都不是實際上相同,因爲您*重定向*執行'/ dev/null',而* pipe *到'Out-Null'。 – Joey

+0

@Joey更正,因爲'/ dev/null'被表示爲一個文件。感謝您指出。 –

+0

我更新了我的問題以更好地描述我的代碼。我試過了你的建議,但它對我沒有幫助。因爲當我重定向輸出時,當我調用它時,下一個函數中的Config變量是空的。 – zosim

0

幾個選項:

# Pipe to the Out-Null cmdlet 
$Config | Out-Null 

# Cast to void 
[void]$Config 

# assign to $null 
$null = $Config 

# redirect to $null 
$Config > $null