pghtech
pghtech

Reputation: 3702

Problems returning hashtable

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 state just....

$siteInfo

And it will return

else

Key: site
Value: Something
Name: site

Key: app
Value: else
Name: app

What am I missing?

Upvotes: 7

Views: 19828

Answers (2)

mr.buttons
mr.buttons

Reputation: 695

@Rynant VERY helpful post, thank you for providing examples on hiding function output!

My proposed solution:

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

$c = DoSomething $Site $App

Upvotes: 2

Rynant
Rynant

Reputation: 24283

In PowerShell, functions return any and every value that is returned by each line in the function; an explicit return statement is not needed.

The String.IndexOf() method returns an integer value, so in this example, DoSomething returns '2' and the hashtable as array of objects as seen with .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 a 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

Upvotes: 20

Related Questions