N
N
NewDevLab2020-05-09 23:18:02
PowerShell
NewDevLab, 2020-05-09 23:18:02

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

2 answer(s)
M
MaxKozlov, 2020-05-10
@MaxKozlov

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

then, depending on the parameters formed in the hash, everything that is needed will be called. Switches are
perfectly attached in the Start-Process -Wait: $isWait style
In general, all parameter values ​​can be passed not through a space, but through a colon, this is how splatting forms them.
And inside the function there is an automatic variable $PSBoundParameters in which there is a hash of the passed parameters and their values, and from there you can find out whether the parameter was passed explicitly or received a default value (by checking if there is a key)
Or you can make proxy functions like
Function Get-OtherCompProcess {
Param(
#здесь все обычные параметры для get-process кроме computername
)}
$PSBoundParameters.computername='othercomp'
Get-Process @PSBoundParameters

A
azarij, 2020-05-09
@azarij

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 question

Ask a Question

731 491 924 answers to any question