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:
- Set
$arg1to a value that must be determined when the script runs, for example, the host IP address. - Print the default value of
$arg1within the.PARAMETER arg1help 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.