在PowerShell中输出函数结果的方法是使用Write-Host命令。

3

我试图将 $x = [System.Net.Dns]::GetHostAddresses($name) 语句的结果写入我的 write-host 字符串中,但是在将函数的结果输出时遇到了一些问题。

以下是相关代码:

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)"""}

目前它只是直接输出字符串,但当它到达"fu"子表达式时,似乎不能正确执行逻辑,而只是字面上输出"$x",我的意图是使其输出foreach-object语句中当前对象的IP。


[System.Net.Dns]::GetHostAddresses(<<hostname>>) | Get-Member 没有显示任何 value 属性?你可以先在你的 ISE / 控制台中运行 [System.Net.Dns]::GetHostAddresses(<<hostname>>) 来尝试。 - Angshuman Agarwal
你是不是想用这种方式 - [System.Net.Dns]::GetHostAddresses("<<hostname>>")[0].ToString() 替换 function fu() 中的内容? - Angshuman Agarwal
将$x更改为类似于:$x = [System.Net.Dns] :: GetHostAddresses($name) | select-object IPAddressToString -expandproperty IPAddressToString的内容? - AA11oAKas
是的,但它会返回多个值。对吧? - Angshuman Agarwal
我想从foreach-object命令中调用fu函数,并向其提供当前对象$.Name,以便它返回与指定的$ .Name相关联的单个IP地址。 - AA11oAKas
如果我在Get-ADComputer cmdlet中的$(fu $.Name)处内联插入[System.Net.Dns] ::GetHostAddresses($.Name),那么它会给我想要的结果,但我无法应用“如果地址为空,则…”逻辑。 - AA11oAKas
3个回答

1

我对代码进行了一些扩展以进行说明,但请尝试这样做:

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

它可以做你想要的,$a是一组数据。但你必须了解以下函数会给出不同的结果。

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

最后一个再次给出了良好的结果。 returnwrite-out 都会将数据写入函数的输出中。 Write-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

1

这是因为你把$x放在花括号{}里面了。

只需要执行Write-Host $x即可。


哇...今天我参加了太多的会议,哈哈,谢谢SpellingD。 - AA11oAKas

0

[System.Net.Dns]::GetHostAddresses(<<hostname>>) | Get-Member 没有显示任何 value 属性?

您可以尝试使用 this 函数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接