Parameter set cannot be resolved with mutually exclusive non default parameters - powershell

Following is full param block signature, I tried almost every possible solution that I'm aware of such as
adding Mandatory to File and Thumbprint parameters sets, removing default parameter set etc, none of which works.
Problem description and desired functionality is this:
Domain parameter is always required while File and ThumbPrint are optional but mutually exclusive.
I run this test as follows:
.\Set-WinRM* -Domain VM-PRO
Parameter set cannot be resolved using the specified named parameters.
function Set-WinRM
{
[CmdletBinding(PositionalBinding = $false, DefaultParameterSetName = "None")]
param (
[Parameter()]
[ValidateSet("HTTP", "HTTPS", "Any")]
[string] $Protocol = "HTTPS",
[Parameter(Mandatory = $true)]
[Alias("ComputerName", "CN")]
[string] $Domain,
[Parameter(ParameterSetName = "File")]
[string] $CertFile,
[Parameter(ParameterSetName = "ThumbPrint")]
[string] $CertThumbPrint,
[Parameter()]
[switch] $SkipTestConnection,
[Parameter()]
[switch] $ShowConfig
)
}
EDIT:
I never use dynamic parameters, if this can't be done normally maybe you can provide an example on how to define them in this example, that would be great.

I copy and pasted your code into Powershell ISE, and added echo $domain to the end to test the parameter. It returns the value normally, without errors:
I don't see any issues with your parameter block, which leads me to believe something else is at fault. If you type out .\Set-WinRM.ps1 -Do, or Set-WinRM -Do can you tab-complete it successfully? If you run Set-WinRM without parameters at all, does it prompt you for Domain:?
I would only expect to see that error if you had additional parameter sets with $domain doing different things, or maybe if a module you have loaded has the Set-WinRM command and it's taking precedence. Try Get-Command Set-WinRM and make sure the CommandType is Function and the Source is blank.

Related

Pipeline input not being validated when a function emits no output down the pipeline for ValueFromPipelineByPropertyName parameters

I was able to reproduce this in a more generic way, and the issue is different than originally presented. I have rewritten this question to reflect the issue experienced along with a generic reproducible example.
I have a cmdlet that sometimes produces no output when it doesn't find any data to return. However, I use this function to pass information to another cmdlet which accepts pipeline input via way of the ValueFromPipelineByPropertyName attribute. When there is an actual object being passed down the pipeline, everything works as expected, including parameter validation checks. However, if the passed object is $null, then parameter validation gets skipped. Note that this is not reproduceable when simply passing $null down the pipeline; I've only been able to reproduce this when emitting no output down the pipeline.
I've been able to reproduce this generically. The parameters are defined with the same attributes as my real code:
Function Get-InfoTest {
Param(
[switch]$ReturnNothing
)
if( !$ReturnNothing ) {
[PSCustomObject]#{
Name = 'Bender'
Age = [int]::MaxValue
}
}
}
Function Invoke-InfoTest {
Param(
[Parameter(Mandatory, ValueFromPipelineByPropertyName)]
[string]$Name,
[Parameter(Mandatory, ValueFromPipelineByPropertyName)]
[int]$Age
)
Write-Host "Hello, $Name. I see you are $Age years old."
}
# With valid object
Get-InfoTest | Invoke-InfoTest
# Correct behavior when $null is directly passed into the cmdlet, throws error
$null | Invoke-InfoTest
# With returned null object, should throw an error but executes with an incorrect result
Get-InfoTest -ReturnNothing | Invoke-InfoTest
What is going on here? While it's not difficult to write null-or-whitespace checks in the function body, this is the point of the Mandatory parameter option as well as the Validate* parameter attributes. In my real code, I now need to write null-or-whitespace checks for several parameters which already have validation attributes set. As stated in the code comments, passing $null into the target cmdlet results in the correct error being thrown, but no output produced from a function results in the function executing as if everything was provided correctly.
If you don't define begin/process/end blocks, functions bodies default to an end block. However, putting the function body in an explicit process block results in the correct behavior:
The following modification to Invoke-InfoTest results in the sample code working correctly for all cases:
Function Invoke-InfoTest {
Param(
[Parameter(Mandatory, ValueFromPipelineByPropertyName)]
[string]$Name,
[Parameter(Mandatory, ValueFromPipelineByPropertyName)]
[int]$Age
)
# Note that I've wrapped this in a process block
process {
Write-Host "Hello, $Name. I see you are $Age years old."
}
}
This works because as stated above, functions default to an end block if unspecified. However, the end and begin blocks are executed regardless of the pipeline object being input. process only gets executed when there is data passed in. Defining the code using the pipeline variables inside of a process block effectively stops the code using the missing data from being executed, which seems to be by design.
Thanks to #SantiagoSquarzon in the comments for helping me realize the actual problem.

Trying to use parameters dynamically using powershell

I am trying to setup dynamic parameters that vary depending on if you are adding or modifying/removing a drone. Ex: If you are adding a drone you would need its IP/Name/Location.. To remove the drone you would only need its name. I have tried looking online and try various examples I've seen but I am completely stuck here. Any help to steer me in the right direction would be appreciated. I am somewhat new to powershell. Here's what I have.
[CmdletBinding(SupportsShouldProcess=$True)]
Param( [Parameter(Mandatory=$true,
HelpMessage = "Add remove or Modify a drone?")]
[ValidateSet("Add", "Remove", "Modify")]
[String]$Action)
DynamicParam{
if ($action = "Add"){
Param( [Parameter(Mandatory)]
[ValidateSet("NorthAmerica", "SouthAmerica", "NorthernEurope","UK", "CEE", "FRMALU", "SouthernEurope", "AsiaPacific")]
[String]$curRegion,
[Parameter(Mandatory)]
[IPAddress]$ip,
[Parameter(Mandatory)]
[String]$droneName)
}
if ($action = "Remove"){
Param(
[Parameter(Mandatory)]
[string]$droneRemoveName)
}
}
Consider driving your parameter constraints with named Parameter Sets instead. I'm suggesting this because dynamic parameters don't work quite like you think they do, but named parameter sets are an easier way to solve your problem. In case you're interested, here's a blog post explaining how to use dynamic parameters and it winds up being pretty manual parameter handling.
You can add a parameter to more than one parameter set depending on the contexts in which each parameter is required. Instead of using -Action ACTION as a driver for a dynamic parameter, use a [switch] instead, such as -Add and -Remove, and have each switch part of its own parameter set. For example, when defining your parameters, it may look something like this:
Param(
[Parameter(ParameterSetName='Remove')]
[switch]$Remove,
[Parameter(ParameterSetName='Add')]
[switch]$Add,
[Parameter(ParameterSetName='Remove', Mandatory)]
[Parameter(ParameterSetName='Add', Mandatory)]
[string]$IPAddress
)
In this example, -IPAddress is valid when you use the -Add or -Remove switch, but won't be relavant outside of this context. Of course, if a parameter should only be valid for a certain parameter set, don't define it under more than one parameter set name.
If you want to make sure at least one "action" switch is defined before executing, you can check that one of those parameters was used when invoking the cmdlet by checking $PSBoundParameters:
('Add' -in $PSBoundParameters.Keys) -Or ('Remove' -in $PSBoundParameters.Keys)

Handling boolean values for String parameters in Powershell

Using Powershell I'd like to call my script as follows:
myscript.ps1 -device1 enable -device2 disable -device3 enable
Each device paramenter is defined as String followed by a bool value.
param(
[string] $device1,
[string] $device2,
[string] $device3
)
Does PowerShell support this with some predefined functions or parameters or would you implement this in a totally different way? I'd like to avoid a parsing for enable and disable.
I would implement this using a switch:
param(
[switch] $device1,
[switch] $device2,
[switch] $device3
)
So you can invoke your script using:
myscript.ps1 -device1 -device3

Parameter, if switch is present, don't permit other parameters

I have a function with parameters like this:
param(
[string[]]$ComputerName,
[string]$exepath,
[string[]]$exeargs,
[switch]$help
)
If the User who uses this function uses the -help switch, there must not be any other parameters declared to call the function. I want to prevent anyone using -help alongside other parameters.
How can I achieve that? I read about_Functions_Advanced_Parameters but it doesn't really help me. I first thought what I need is a ValidateSet but that's different from what I need.
You could use the ParameterSetName attribute:
param(
[Parameter(ParameterSetName='default')]
[string[]]$ComputerName,
[Parameter(ParameterSetName='default')]
[string]$exepath,
[Parameter(ParameterSetName='default')]
[string[]]$exeargs,
[Parameter(ParameterSetName='help')]
[switch]$help
)

How do I declare a parameter type as a .NET framework type that must be explicitly loaded?

I want to be able to pass a Color type from System.Drawing into my PowerShell script. However, unless I explicitly load the System.Drawing.dll prior to running my script and I don't want to have people do that.
I get this error unless I load the dll outside of the script:
Unable to find type [System.Drawing.Color]
My PowerShell Param declaration looks like this:
Param(
[Parameter(Mandatory = $true)][string] $TargetFile,
[Parameter()][int] $Thickness = 1,
[Parameter()][Switch] $UseTopLeftColor = $false,
[Parameter()][System.Drawing.Color] $BorderColor = [System.Drawing.Color]::FromArgb(195,195,195)
)
The code to load the DLL reference is this:
[Void][System.Reflection.Assembly]::LoadFile("C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll")
How can I define a dependency on the DLL for the script and have it automatically reference the DLL?
Add-Type is just a more convenient way of writing [Reflection.Assembly]::LoadFile(). Neither can be used before Param() in a script.
If you want to be able to run the PowerShell script from anywhere, I'd suggest specifying one parameter per basic color, and then calculating the color in the script. That way you can also validate each value:
Param(
[Parameter(Position=0)]
[ValidateRange(0,255)]
[int]$BorderRed = 195,
[Parameter(Position=1)]
[ValidateRange(0,255)]
[int]$BorderGreen = 195,
[Parameter(Position=2)]
[ValidateRange(0,255)]
[int]$BorderBlue = 195
)
Add-Type -Assembly 'System.Drawing'
[Drawing.Color]::FromArgb($BorderRed, $BorderGreen, $BorderBlue)
Trying to specify the color as a list of 3 values to a single parameter would be difficult to implement. From outside PowerShell you can't really pass an array to a parameter, so you'd have to specify something like a comma-separated string and parse that into 3 integer values.
Passing color names as a single parameter would work, though:
Param(
[Parameter()]
[string]$BorderColor = 'Blue'
)
Add-Type -Assembly 'System.Drawing'
[Drawing.Color]::$BorderColor