簡體   English   中英

powershell函數輸出到變量

[英]powershell function output to variable

我在powershell 2.0中有一個名為getip的函數,它獲取遠程系統的IP地址。

function getip {
$strComputer = "computername"

$colItems = GWMI -cl "Win32_NetworkAdapterConfiguration" -name "root\CimV2" -comp $strComputer -filter "IpEnabled = TRUE"



ForEach ($objItem in $colItems)

{Write-Host $objItem.IpAddress}

}

我遇到的問題是將此函數的輸出變為變量。 下面的內容不起作用......

$ipaddress = (getip)
$ipaddress = getip
set-variable -name ipaddress -value (getip)

任何有關這個問題的幫助將不勝感激。

可能這會起作用嗎? (如果使用Write-Host ,則輸出數據,不返回)。

function getip {
    $strComputer = "computername"

    $colItems = GWMI -cl "Win32_NetworkAdapterConfiguration" -name "root\CimV2" -comp $strComputer -filter "IpEnabled = TRUE"

    ForEach ($objItem in $colItems) {
        $objItem.IpAddress
    }
}


$ipaddress = getip

然后, $ipaddress將包含一個字符串IP地址數組。

你也可以這樣做

function getip {
    $strComputer = "computername"

    $colItems = GWMI -cl "Win32_NetworkAdapterConfiguration" -name "root\CimV2" -comp $strComputer -filter "IpEnabled = TRUE"

    ForEach ($objItem in $colItems) {
        write-output $objItem.IpAddress
    }
}


$ipaddress = getip

要在pipline中訪問,你應該使用return / write-output

簡而言之,問題是Write-Host 無法重定向。

您可以利用此行為,例如將信息返回給用戶,當他重定向函數的返回值時將不會捕獲該信息,將其存儲在變量中,但仍然可見。

采用:

  • Write-Host直接寫入(shell)進程 - 而不是流
  • Write-Output寫入success- / output-stream
    • 僅將成功流重定向到文件: Write-Output "success message" 1>output_stream_messages.txt
    • 存儲在變量中: $var=Write-Output "output message"
    • 注意:變量賦值總是重定向output- / success-stream 其他溪流保持不變
  • Write-Error寫入錯誤流
    • 僅將錯誤流重定向到文件: Write-Error "error message" 2>error_stream_messages.txt
    • 存儲在變量中: $var=Write-Error "Error message" 2>&1
    • 注意:這實際上將錯誤流重定向到成功流 已經在成功流中的數據不會被覆蓋,而是被附加。 由於錯誤輸出現在位於成功流中 (我們也可以)通過將成功流數據重定向/分配給變量$var來將其存儲在變量中。
  • Write-Warning以寫入警告流
    • 僅將警告流重定向到文件: Write-Warning "warning message" 3>warning_stream_messages.txt
    • 存儲在變量中: $var=Write-Warning "Warning message" 3>&1
  • Write-Verbose寫入詳細流
    • 僅將verbose-stream重定向到文件: Write-Verbose "verbose message" -Verbose 4>verbose_stream_messages.txt
    • 存儲在變量中: $var=Write-Verbose "Verbose message" -Verbose 4>&1
    • 注意: -Verbose是必需的,因為默認的-Verbose設置不會輸出詳細消息。 (由偏好變量$VerbosePreference定義,通常是“SilentlyContinue” 。你也可以在喚起命令(在當前的PowerShell會話/環境中)之前將其設置為$VerbosePreference="Continue" ,以便不需要切換-Verbose 。) 在這里查看有關powershell首選項變量的更多信息。
  • Write-Debug寫入調試流
    • 僅將調試流重定向到文件: Write-Debug "debug message" -Debug 5>debug_stream_messages.txt
    • 存儲在變量中: $var=Write-Debug "Debug message" -Debug 5>&1
    • 注意:根據您的$ DebugPreference變量的設置,您的powershell可能會暫停並查詢您的輸入以進行下一個選擇的操作。 設置$DebugPreference="Continue"以消除此行為,並且喚起命令之前 -Debug需要-Debug開關。

您可以使用*>&1將所有流重定向到成功流 ,然后根據需要重定向它。 (將其存儲在變量中或將其重定向到$ null或文件或類似的東西。)

有關更多詳細信息,我建議在devblogs.microsoft.com上有關於PowerShell流的非常好的文章

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM