返回哈希表的问题

pgh*_*ech 5 powershell

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

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

$siteInfo = DoSomething
$siteInfo["site"]
Run Code Online (Sandbox Code Playgroud)

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

我可以说......

$siteInfo
Run Code Online (Sandbox Code Playgroud)

它会回来

else

Key: site
Value: Something
Name: site

Key: app
Value: else
Name: app
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

Ryn*_*ant 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()
Run Code Online (Sandbox Code Playgroud)

以下示例显示了阻止不需要的输出的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']
Run Code Online (Sandbox Code Playgroud)

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

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

        $app
    }

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

DoSomething
Run Code Online (Sandbox Code Playgroud)