【问题标题】:output function result in powershell write-host输出函数导致powershell write-host
【发布时间】:2012-06-28 15:33:34
【问题描述】:

我正在尝试编写 $x = [System.Net.Dns]::GetHostAddresses($name) 语句写入我的写入主机字符串,但在将函数的结果输入输出时遇到了一些问题。

以下是相关代码:

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”,我的意图是让它输出当前 obj 的 IP foreach-object 语句。

【问题讨论】:

  • [System.Net.Dns]::GetHostAddresses(<<hostname>>) | Get-Member 没有显示任何value 属性?您可以简单地尝试在您的 ISE / 控制台中首先运行它 - [System.Net.Dns]::GetHostAddresses(<<hostname>>)
  • 您是否打算这样做 - [System.Net.Dns]::GetHostAddresses(">")[0].ToString() in function fu()
  • 将 $x 更改为:$x = [System.Net.Dns]::GetHostAddresses($name)|select-object IPAddressToString -expandproperty IPAddressToString ?
  • 是的,但它会返回多个值。对吧?
  • 好吧,我想从 foreach-object cmd 中调用 fu 函数并为其提供当前的 objs $_.Name,所以我认为它会返回与 obj 连接的单个 IP 地址由其 $_.Name 指定?

标签: function powershell active-directory


【解决方案1】:

这是因为您将$x 放在大括号{} 中。

只要Write-Host $x

【讨论】:

  • 哇...我今天参加了很多会议,哈哈,谢谢 SpellingD
【解决方案2】:

我稍微扩展了解释的代码,但试试这个:

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

【讨论】:

    【解决方案3】:

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

    你可以试试this函数。

    【讨论】:

      猜你喜欢
      • 2023-01-25
      • 1970-01-01
      • 2015-05-19
      • 2012-03-06
      • 2014-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多