Hello Lanky,
Thank you for your question and for reaching out with your question today.
In PowerShell, you can use splatting to achieve optional/dynamic parameters for cmdlets. Splatting allows you to pass a collection of parameter names and their values as a single variable to a cmdlet. This way, you can conditionally include or exclude parameters based on your requirements.
Here's how you can modify your code using splatting to make the -DefaultGateway
parameter optional:
$AddGW = $True
$Adapter = Get-NetAdapter | Where-Object { $_.InterfaceDescription -match "Intel" }
# Define the common parameters that are always used
$parameters = @{
IPAddress = "********"
PrefixLength = 24
}
# Add the DefaultGateway parameter if $AddGW is true
if ($AddGW) {
$parameters.Add("DefaultGateway", "1.1.1.1")
}
$Adapter | New-NetIPAddress @parameters
In this code, we first define a hashtable $parameters
that includes the common parameters -IPAddress
and -PrefixLength
, which are always used. Then, we conditionally add the -DefaultGateway
parameter to the hashtable if the variable $AddGW
is $True
. Finally, we use splatting (@parameters
) to pass the parameters to the New-NetIPAddress
cmdlet.
With this approach, you can easily add or remove optional parameters without having to repeat the entire command. The code remains concise and easier to manage.
I used AI provided by ChatGPT to formulate part of this response. I have verified that the information is accurate before sharing it with you.
If the reply was helpful, please don’t forget to upvote or accept as answer.