3

我在 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)

对此问题的任何帮助将不胜感激。

4

3 回答 3

6

可能这会起作用吗?(如果使用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 地址数组。

于 2010-06-10T18:32:09.553 回答
2

你也可以

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

要在管道内访问,您应该使用 return/write-output

于 2012-02-13T13:43:05.380 回答
1

简而言之,问题是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写入详细流
    • 仅将详细流重定向到文件:Write-Verbose "verbose message" -Verbose 4>verbose_stream_messages.txt
    • 存储在变量中:$var=Write-Verbose "Verbose message" -Verbose 4>&1
    • 注意:这-Verbose是必要的,因为默认的 powershell 设置不输出详细消息。(由首选项变量定义$VerbosePreference,通常为"SilentlyContinue"。您也可以$VerbosePreference="Continue"在调用命令之前(在当前的 powershell 会话/环境中)将其设置为不需要开关-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也不需要切换。

您可以使用*>&1将所有流重定向到成功流,然后根据需要将其重定向。(将其存储在变量中或将其重定向到$null或文件或类似的东西。)

有关更多详细信息,我推荐在 devblogs.microsoft.com 上一篇关于 powershell 流的非常好的文章

于 2019-09-04T08:20:17.810 回答