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?
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
@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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With