Reputation: 11
I am new to powershell and i am trying to understand the output of this script.
Can someone please provide an explanation of the output?
$a = 4 ;
$b = 3 ;
function fun ($a = 3 , $b = 4)
{
$c = $a + $b / $b + $a;
echo "$c";
}
echo $a;
echo $b;
echo $c;
fun($a,$b);
Upvotes: 0
Views: 190
Reputation: 28963
Let's change the script to make it more idiomatic and more clear (changed listed at the end):
function Test($paramA = 30, $paramB = 40)
{
$testC = $paramA + ($paramB / $paramB) + $paramA
"$testC"
}
$outerA = 4
$outerB = 3
$outerA
$outerB
$outerC
Test @($outerA, $outerB)
What happens is:
$outerA
and $outerB
have values assigned.$outerA
and $outerB
are named, and print their values, once per line. 4
and 3
.$outerC
is named, it has not been used before and has no value (this is not an error in PowerShell), nothing is printed.Test
is called with no named parameters and an array in first position.$paramA
.$paramB = 40
.$testC = $paramA + ($paramB / $paramB) + $paramA
becomes $testC = @(4,3) + (40/40) + @(4,3)
.(@(4,3) + 1) + @(4, 3)
which adds things onto the end of the first array and makes an array @(4, 3, 1, 4, 3)
."$testC"
is a string, using double quotes which means you can put variables in it and they get turned into text.@(4, 3, 1, 4, 3)
becomes the text "4 3 1 4 3"
Test @($outerA, $outerB)
.Code output:
4 # from outerA
3 # from outerB
4 3 1 4 3 # from outerA outerB (paramB/paramB) outerA outerB
30 is nowhere in the output because paramA is given a value, so the default is not used. 40 is nowhere in the output because 40/40 == 1.
Changes:
;
because it is only needed if you want to put many things on the same line.()
around the calculation to make order of precedence clearer, divide happens before add.@
in front of ($outerA,$outerB)
to make it more clear that's an array, not the function parameters.echo
, it is an alias for Write-Output
and is the default thing which happens to variables if you just write their name.Upvotes: 2
Reputation: 15
so the script initializes $a to be 4 and $b to be 3.\
$a = 4 ;
$b = 3 ;
the function needs $a and $b parameters that are set to be 4 and 3 by deafault.
then it calculates $c = $a + $b / $b + $a
then prints the resault.
function fun ($a = 3 , $b = 4) {
$c = $a + $b / $b + $a;
echo "$c";
}
the script prints $a then $b then $c.
echo $a;
echo $b;
echo $c;
then the function fun
is called.
fun ($a, $b);
output:
4
3
4 3 1 4 3
if you want the function fun
to calculate %c probably you need to use
fun $a $b;
output:
4
3
9
Upvotes: 0