How do I handle two different input parameters in a PowerShell function?

0
30
Asked By AdventurousFox42 On

I'm trying to create a PowerShell function that can take either a string array for application names or an integer array for CI IDs. Both these parameters need to support pipeline input by property name since I'd like to pass an object, specifically an SCCM application. When I get to the process block, I need to iterate over the input array, but since I might be working with either of the two, I'm wondering if I should structure it like this:

```powershell
process {
if ($PsBoundParameters['Name']) {
foreach ($app in $Name) {
# Do several things
}
}
if ($PsBoundParameters['CI_ID']) {
foreach ($app in $CI_ID) {
# Do all of those same things
}
}
}
```

5 Answers

Answered By QuickFix247 On

If you're on the move and need a quick hack, you could try something like this: `foreach($app in ( @() + $Name + $CI_ID ))` to handle both inputs at once. It’s a bit unconventional but might work for your situation!

Answered By FunctionFanatic23 On

It sounds like you're getting an application by either name or ID and then doing something with it. You can set this up using parameter sets in your function like this:

```powershell
function Do-Something {
[CmdletBinding(DefaultParameterSetName = "ByName")]
Param (
[Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = "ByName")]
[string[]]
$AppName,

[Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = "ById")]
[int[]]
$AppId
)
Process {
$FoundApps = if ($PSBoundParameters.ContainsKey('AppName')) {
GetAppsByName $AppName
} else {
GetAppsById $AppId
}
foreach ($App in $FoundApps) {
# Do something.
}
}
}
```

Answered By CuriousCoder99 On

You might want to simplify your parameters to accept a single string or int instead of an array. This way, you can just pass different objects through the pipeline, and your function can handle the looping for you. But keep in mind that this approach may not support input like `yourFunction -Name "stuff1", "stuff2", "stuff3"` which accepts multiple names. Your current setup should work, but you might also want to check for null values during processing as an additional safety check.

Answered By AppGuru88 On

What does your input object look like? Which CIM class are you using? If both properties might not show up at the same time, I suggest choosing one as a primary and using the other as an alias for better handling.

Answered By SmartScripter56 On

You're likely overlooking a simple solution. If you're passing either a list of names or IDs, you can connect one to the other before iterating. Using parameter sets allows you to switch between them cleanly, leveraging commands to get apps by name or ID based on which one you provided during the call.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.