Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

powershell function output to variable

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.

like image 285
tommy Avatar asked Jan 01 '26 09:01

tommy


1 Answers

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.

like image 124
Nate Pinchot Avatar answered Jan 04 '26 13:01

Nate Pinchot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!