Share via

Can I call a cmdlet using variable?

Ana 141 Reputation points
2020-10-08T21:44:56.223+00:00

I have a function with 34 parameters that looks roughly like this:

function ABCDE{
[CmdletBinding()]
param (
[Parameter()]
[Switch] $MyObject,
[Parameter()]
[Switch] $OptionA,
[Parameter()]
[Switch] $OptionB,
[Parameter()]
[Switch] $OptionC
)

if($OptionA)
{
Set-OptionA -Object $Myobject
}

if($OptionB)
{
Set-OptionB -Object $Myobject
}

}

and so on for 34 parameters...

Can I somehow clean up it and use one foreach instead? I would see it like this:

function ABCDE{
[CmdletBinding()]
param (
[Parameter()]
[Switch] $MyObject,
[Parameter()]
[Switch] $OptionA,
[Parameter()]
[Switch] $OptionB,
[Parameter()]
[Switch] $OptionC
)

foreach($parameter in $this.Parameters){
if($parameter.IsPresent){
Set-$parameter.Name -Object $MyObject
}
}

Is something like this possible? To use parameter in the cmdlet name?

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments

Answer accepted by question author

Anonymous
2020-10-09T06:54:02.587+00:00

Hi Ana,
You could use $PSBoundParameters to get the parameters passed to the function and use & to run a command. The script could be like this

foreach ($Parameter in $PSBoundParameters.Keys) {  
    if ($parameter -ne "MyObject") {  
        $cmd = "Set-" + $Parameter  
        &$cmd -Object $MyObject  
    }  
}  

When you run ABCDE -OptionA -OptionB -MyObject $obj, the function will call Set-OptionA -Object $obj and Set-OptionB -Object $obj

Best Regards,
Ian

============================================

If the Answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

Was this answer helpful?

1 person found this answer helpful.
0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Rich Matheisen 48,116 Reputation points
    2020-10-09T02:10:43.703+00:00

    Yes, you can.

    function p1{
        param(
            $MyObject,
            [array]$Options
        )
    
        function Set-OptionA{
            param($obj)
            "Setting OptionA - $obj"
        }
        function Set-OptionB{
            param($obj)
            "Setting OptionB - $obj"
        }
    
        $Options |
            ForEach-Object{
                Invoke-Expression "Set-Option$_ $MyObject"
            }
    }
    
    p1 "Boo" "A","B"
    p1 $false "A","C", "B"
    

    Was this answer helpful?

    1 person found this answer helpful.

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.