views:

140

answers:

1

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.

+2  A: 

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.

Nate Pinchot
More specifically, Write-Host sends the data directly to the console host or stdout of the process.Write-Output or not capturing the output (as in Nate's example) will send the output to "stdout" of the current pipeline or function. This is approximately the same behavior as "echo" in a batch file.
JasonMArcher