Powershell 返回哈希表的问题

Powershell 返回哈希表的问题,powershell,Powershell,因此,如果我有以下代码: function DoSomething { $site = "Something" $app = "else" $app return @{"site" = $($site); "app" = $($app)} } $siteInfo = DoSomething $siteInfo["site"] 为什么$siteInfo[“site”]不返回“Something” 我可以说 $siteInfo 它会回来的 else Key: site Val

因此,如果我有以下代码:

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

我缺少什么?

在PowerShell中,函数返回函数中每一行返回的任何值;不需要显式的
return
语句

String.IndexOf()
方法返回一个整数值,因此在本例中,
DoSomething
将“2”和哈希表作为对象数组返回,如
.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']
function DoSomething {
    # The Dot-operator '.' executes the ScriptBlock in the current scope.
    $null = .{
        $site = "Something"
        $app = "else"

        $app
    }

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

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

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']
function DoSomething {
    # The Dot-operator '.' executes the ScriptBlock in the current scope.
    $null = .{
        $site = "Something"
        $app = "else"

        $app
    }

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

DoSomething

@Rynant非常有用的帖子,感谢您提供隐藏函数输出的示例

我提议的解决办法:

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

$c = DoSomething $Site $App

$siteInfo[“site”]
确实为我返回了
一些东西
。对我来说也是,powershell版本?好的,我有一些更多信息。我在函数代码中添加了一个变量($app)的简单调用。发生的事情是$app和哈希表中的值被返回给调用函数的变量。因此,如果我做($siteInfo | fl),它将同时显示“else”,然后显示两个键/值。这是为什么呢?似乎因为您在一行中单独拥有
$app
,所以您希望在函数本身的屏幕上打印一些内容,但不将其返回给调用者。可以使用
Out-Host
Write-Host
cmdlet执行此操作,该cmdlet将显示对象,但不会将其提交到管道。例如:
Write Host$app
Write Host$app | Out Host
@Thank Rynant-在本例中,没有更好的方法来管理返回值。设置变量是很常见的,但必须返回并阻止所有可能返回的值,这会将几行函数变成一团乱麻。你能过滤一下吗,例如>函数名|$\。要获得返回值?@pghtech-实际上,我没有发现我需要显式阻止返回值的次数不多,因为我通常使用返回值或没有返回值。虽然我不知道我是否在实践中见过它,但我想你可以用
$null=.{}来包装一切,但我宁愿在必要时使用
Out null`之类的东西。说真的,为什么?差点砸了我的笔记本电脑,想做些***功能!为什么额外的
$()
用于
$site
$app
?@dc7a9163d9可能不需要。我只是在修改问题中的代码。