powershell function output to variable

2019-07-03 06:19发布

问题:

I have a function in powershell 2.0 named getip which gets the IP address(es) of a remote system.

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}

}

The problem I'm having is with getting the output of this function to a variable. The folowing doesn't work...

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

any help with this problem would be greatly appreciated.

回答1:

Possibly this would work? (If you use Write-Host, the data will be output, not returned).

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 will then contain an array of string IP addresses.



回答2:

you can allso do

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

for accessing within the pipline you should use return/write-output