Create a function with optional call variables
Powershell provides a lot of built-in support for common parameter scenarios, including mandatory parameters, optional parameters, "switch" (aka flag) parameters, and "parameter sets."
By default, all parameters are optional. The most basic approach is to simply check each one for $null
, then implement whatever logic you want from there. This is basically what you have already shown in your sample code.
If you want to learn about all of the special support that Powershell can give you, check out these links:
I don't think your question is very clear, this code assumes that if you're going to include the -domain parameter, it's always 'named' (i.e. dostuff computername arg2 -domain domain); this also makes the computername parameter mandatory.
Function DoStuff(){ param( [Parameter(Mandatory=$true)][string]$computername, [Parameter(Mandatory=$false)][string]$arg2, [Parameter(Mandatory=$false)][string]$domain ) if(!($domain)){ $domain = 'domain1' } write-host $domain if($arg2){ write-host "arg2 present... executing script block" } else{ write-host "arg2 missing... exiting or whatever" }}
Not sure I understand the question correctly.
From what I gather, you want to be able to assign a value to Domain if it is null and also what to check if $args2 is supplied and according to the value, execute a certain code?
I changed the code to reassemble the assumptions made above.
Function DoStuff($computername, $arg2, $domain){ if($domain -ne $null) { $domain = "Domain1" } if($arg2 -eq $null) { } else { }}DoStuff -computername "Test" -arg2 "" -domain "Domain2"DoStuff -computername "Test" -arg2 "Test" -domain ""DoStuff -computername "Test" -domain "Domain2"DoStuff -computername "Test" -arg2 "Domain2"
Did that help?