返回哈希表的问题

时间:2011-12-29 18:13:54

标签: powershell

所以,如果我有以下代码:

function DoSomething {
  $site = "Something"
  $app = "else"
  $app
  return @{"site" = $($site); "app" = $($app)}
}

$siteInfo = DoSomething
$siteInfo["site"]

为什么$ siteInfo [“site”]不返回“Something”?

我可以说明......

$siteInfo

它将返回

else

Key: site
Value: Something
Name: site

Key: app
Value: else
Name: app

我错过了什么?

2 个答案:

答案 0 :(得分:16)

在PowerShell中,函数返回函数中每行返回的任何值;

。不需要明确的return语句。

String.IndexOf()方法返回一个整数值,因此在此示例中,DoSomething返回' 2'和哈希表作为.GetType()所见的对象数组。

function DoSomething {
  $site = "Something"
  $app = "else"
  $app.IndexOf('s')
  return @{"site" = $($site); "app" = $($app)}
}

$siteInfo = DoSomething
$siteInfo.GetType()

以下示例显示了阻止不需要的输出的3种方法:

function DoSomething {
  $site = "Something"
  $app = "else"

  $null = $app.IndexOf('s')   # 1
  [void]$app.IndexOf('s')     # 2
  $app.IndexOf('s')| Out-Null # 3

  # Note: return is not needed.
  @{"site" = $($site); "app" = $($app)}
}

$siteInfo = DoSomething
$siteInfo['site']

以下是如何在ScriptBlock中包装多个语句以捕获不需要的输出的示例:

function DoSomething {
    # The Dot-operator '.' executes the ScriptBlock in the current scope.
    $null = .{
        $site = "Something"
        $app = "else"

        $app
    }

    @{"site" = $($site); "app" = $($app)}
}

DoSomething

答案 1 :(得分:1)

@Rynant非常有用的帖子,感谢您提供有关隐藏功能输出的示例!

我建议的解决方案:

function DoSomething ($a,$b){
  @{"site" = $($a); "app" = $($b)}
}

$c = DoSomething $Site $App