Hash Table Return Issues

So, if I have the following code:

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

$siteInfo = DoSomething
$siteInfo["site"]

Why doesn't $ siteInfo ["site"] return "Something"?

I can only say ....

$siteInfo

And he will return

else

Key: site
Value: Something
Name: site

Key: app
Value: else
Name: app

What am I missing?

+5
source share
2 answers

In PowerShell, functions return any values ​​returned by each line in a function; an explicit statement is returnnot needed.

The method String.IndexOf()returns an integer value, so in this example it DoSomethingreturns "2", and the hash table as an array of objects, as shown in .GetType().

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

$siteInfo = DoSomething
$siteInfo.GetType()

The following example shows 3 ways to block unwanted output:

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']

Here is an example of how to wrap multiple statements in ScriptBlock to capture unwanted output:

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

        $app
    }

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

DoSomething
+12

@Rynant , !

:

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

$c = DoSomething $Site $App
+1

All Articles