Reputation: 418
I am attempting to call a function in powershell, but pass it variables so I don't need to repeat the funxtion X amount of times with different values. I would like it so that, when I call the function I simply type:
Foo(Red,12,1.8)
And the generic function, foo, as follows:
function Foo(Colour, Age, Height){
<# Function does something with data here #>
}
Is this possible using powershell, and if so, would any changes made to those variables be saved after the function has completed?
Upvotes: 1
Views: 804
Reputation: 1570
Yes you can use parameters in functions.
By default the parameters only change within the scope of the function, but you can choose to return the same parameters as results if you like.
example (uses splatting)-
function Foo{
param(
[string]$Color,
[int]$Age,
[decimal]$Height
)
$Age += 1
$Height += 1
$ExampleOutput = [ordered]@{
Color = $Color
Age = $Age
Height = $Height
}
return ($ExampleOutput)
}
$Parameters = @{
Color = "Red"
Age = 12
Height = 1.8
}
Foo @Parameters
Upvotes: 2
Reputation: 15508
Yes try default values:
function Foo($Colour='Red',$Age=12,$Height=1.8){
<# Function does something with data here #>
}
Upvotes: 1