Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems returning hashtable

Tags:

powershell

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?

like image 330
pghtech Avatar asked Dec 29 '11 18:12

pghtech


2 Answers

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
like image 89
Rynant Avatar answered Oct 21 '22 04:10

Rynant


@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
like image 45
mr.buttons Avatar answered Oct 21 '22 04:10

mr.buttons