Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

output function result in powershell write-host

i'm attempting to write the result of the $x = [System.Net.Dns]::GetHostAddresses($name) statement into my write-host string but am encounter some issues with getting the result from the function into the output.

here's the relevant code:

Import-Module activedirectory

function fu($name)
{
 $x = [System.Net.Dns]::GetHostAddresses($name).value
if ($x -ne $null){
    Write-Host{ $x } 
}
else{
    Write-Host{"Null"} 
}
}

Get-ADComputer -SearchBase 'OU=CorpServers,DC=corp,DC=com,DC=net' -Server      "corp.com.net" -Filter * -Properties * |ForEach-Object{write-host "add filter filterlist=""L2-Windows Servers"" srcaddr=any dstaddr=$(fu $_.Name) description=""$($_.Name)"""}

currently it just outputs the string as is, but when it reaches the fu subexpression seems to not properly perform the logic and only outputs "$x" literally, where my intent was to have it output the IP of the current obj in the foreach-object statement.

like image 456
AA11oAKas Avatar asked Jul 01 '26 23:07

AA11oAKas


2 Answers

It's because you put $x in curly brackets {}.

Just do Write-Host $x

like image 65
SpellingD Avatar answered Jul 04 '26 23:07

SpellingD


I expand a bit the code for the explanation but try this :

function fu($name)
{
  $res = $null
  $x = [System.Net.Dns]::GetHostAddresses($name)
  if ($x -ne $null)
  {
     $res = $x
  }
  return $res
}

$a = fu "localhost"
$a
$a.gettype().fullname

It does what you want, $a is an array of data. But you have to understand that the following functions gives different results

function fu($name)
{
  $res = $null
  $x = [System.Net.Dns]::GetHostAddresses($name)
  if ($x -ne $null)
  {
     $res = $x
  }
  Write-Host $res
}

Clear-Host
$a = fu "localhost"
$a
$a | Get-Member

The las one give again the good result. return and write-out both write data in the output of the function. Write-host just write to the host.

function fu($name)
{
  $res = $null
  $x = [System.Net.Dns]::GetHostAddresses($name)
  if ($x -ne $null)
  {
     $res = $x
  }
  Write-output $res
}

Clear-Host
$a = fu "localhost"
$a
$a | Get-Member
like image 39
JPBlanc Avatar answered Jul 05 '26 00:07

JPBlanc



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!