Answer the question
In order to leave comments, you need to log in
Calling a function with a default parameter?
How to do to call the function in the second option?
function MyFunc() {
param (
[Alias("Param1")] [parameter(Mandatory=$false)] [string] $var1 = $null,
[Alias("Param2")] [parameter(Mandatory=$false)] [string] $var2 = $null
)
Write-Host "*** '$var1' '$var2' ***"
}
# Вызывать не так
MyFunc -Param1 "" -Param2 "param2"
MyFunc -Param2 "param2"
# А так
MyFunc -Param1 -Param2 "param2"
Answer the question
In order to leave comments, you need to log in
For these purposes, it is better to use not the formation in the form of a string, but the so-called Splatting
$params = @{
Param1 = "value1"
}
if ($something) { $params.Param2 = "*value" }
MyFunction @params
Function Get-OtherCompProcess {
Param(
#здесь все обычные параметры для get-process кроме computername
)}
$PSBoundParameters.computername='othercomp'
Get-Process @PSBoundParameters
What is the end goal of this exercise? while it is not clear the meaning of calling the function in this way. if you specify a parameter when calling, then you need to put some value in the parameter.
perhaps you need something like a switch parameter?
function Switch-Item {
param ([switch]$on)
if ($on) { "Switch on" }
else { "Switch off" }
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question