complex default values for powershell script Params

Viewed 76

I would like to set a default Param value that must be determined at script runtime (cannot be hardcoded).

Given powershell script file.ps1

<#
.PARAMETER arg1
    The first argument. Defaults to ???
#>
Param (
    [string] $arg1,
)

I would like:

  1. Set $arg1 to a value that must be determined when the script runs, for example, the host IP address.
  2. Print the default value of $arg1 within the .PARAMETER arg1 help message.

Typically I might add

$arg1_default = (Test-Connection -ComputerName "www.google.com" -Count 1).Address.IPAddressToString

<#
.PARAMETER arg1
    The first argument. Defaults to $arg1_default.
#>
Param (
    [string] $arg1 = $arg1_default,
)

However, in Powershell, the Param statement must be the first processed statement. If I add any complex statements before Param statement then it results in an error:

PS> .\file.ps1
Param: file.ps1:9
Line |
   9 |  Param (
     |  ~~~~~
     | The term 'Param' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the
     | name, or if a path was included, verify that the path is correct and try again.

How do I set default values for a powershell script Param ?



I'm using Powershell 7.

1 Answers

You can use a function with [CmdletBinding()] attribute like Toto in the file test.ps1 defining a default value for a particular parameter for this CmdLet with $PSDefaultParameterValues

# Test.ps1    
$PSDefaultParameterValues["Toto:arg1"]=Invoke-Command -ScriptBlock {(Test-Connection -ComputerName "www.google.com" -Count 1).IPV4Address.IPAddressToString}
Function Toto
{
  [CmdletBinding()]
  Param ([string] $arg1)
  Write-Output $arg1
}

Now in the script where you want to use this (or these) function(s) you can first dot source the.ps1 file that contains the function(s), then call your function toto

. /Test.ps1
Toto  # without argument gives "172.217.18.196" for me now
Toto titi  # With argument give "titi"
Related