Create a function with optional call variables

后端 未结 3 359
南笙
南笙 2021-01-01 11:39

Is there a way to create a parameter in a PowerShell function where you have to call it in order to have it considered?

An example given by commandlet (the bold bein

相关标签:
3条回答
  • 2021-01-01 11:42

    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"
        }
    }
    
    0 讨论(0)
  • 2021-01-01 11:50

    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:

    about_Functions

    about_Functions_Advanced

    about_Functions_Advanced_Parameters

    0 讨论(0)
  • 2021-01-01 11:58

    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?

    0 讨论(0)
提交回复
热议问题