Output powershell function to a variable

I have a function in powershell 2.0 called getip that gets the IP address 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 am facing is getting the result of this function variable. The following does not work ...

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

Any help with this issue would be greatly appreciated.

+3
source share
3 answers

Maybe this will work? (If you use Write-Host, 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 contain an array of string IP addresses.

+6
source

you also can

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 access within the line you must use return / write-output

+2
source

, Write-Host .

, , , , , , .

:

  • Write-Host () ,
  • Write-Output success-/output- .
    • success- : Write-Output "success message" 1>output_stream_messages.txt
    • : $var=Write-Output "output message"
    • : output-/success-.
  • Write-Error
    • : Write-Error "error message" 2>error_stream_messages.txt
    • : $var=Write-Error "Error message" 2>&1
    • . success-. , success-, , ). success-, , / success- $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, success-, . ( $ null, - .)

powershell devblogs.microsoft.com

0

Source: https://habr.com/ru/post/1749459/


All Articles