I am trying to write what seems very simple but I've been going at this for hours and still not able to get what I need.
I have a PowerShell script which will be used for starting up OR shutting down virtual machines. I want to user to specify either a ResourceGroup name, an individual VM name or a text file with the names of the VMs.
This script is used for Azure but the question is specific to the param() declaration.
I have tried every combination I can think of here, making parameters parts of parameter sets, making them mandatory, not mandatory, etc. but I have not been able to get this right.
Any help is appreciated!
param (
[Parameter (Mandatory = $true, ParameterSetName = 'ByResourceGroup')]
[string]$ResourceGroup,
[Parameter (Mandatory = $true, ParameterSetName = 'ByFile')]
[string]$File,
[Parameter (Mandatory = $true, ParameterSetName = 'ByName')]
[string]$Name,
[Parameter (Mandatory = $false, ParameterSetName = 'ByResourceGroup')]
[Parameter (Mandatory = $false, ParameterSetName = 'ByFile')]
[Parameter (Mandatory = $false, ParameterSetName = 'ByName')]
[switch]$Start,
[Parameter (Mandatory = $false, ParameterSetName = 'ByResourceGroup')]
[Parameter (Mandatory = $false, ParameterSetName = 'ByFile')]
[Parameter (Mandatory = $false, ParameterSetName = 'ByName')]
[switch]$Stop
)
The user should be able to pass in EITHER: -ResourceGroup OR -File OR -Name
AND
pass in either: -Start OR -Stop
Not both!
I think I have this correct for the first set but I can't get the -Start and -Stop to be exclusive.
Get-help says this:
SYNTAX
C:\Set-AzureVM.ps1 -ResourceGroup <String> [-Start] [-Stop] [<CommonParameters>]
C:\Set-AzureVM.ps1 -File <String> [-Start] [-Stop] [<CommonParameters>]
C:\Set-AzureVM.ps1 -Name <String> [-Start] [-Stop] [<CommonParameters>]
I am looking for something more like this:
SYNTAX
C:\Set-AzureVM.ps1 -ResourceGroup <String> -Start [<CommonParameters>]
C:\Set-AzureVM.ps1 -File <String> -Start [<CommonParameters>]
C:\Set-AzureVM.ps1 -Name <String> -Start [<CommonParameters>]
C:\Set-AzureVM.ps1 -ResourceGroup <String> -Stop [<CommonParameters>]
C:\Set-AzureVM.ps1 -File <String> -Stop [<CommonParameters>]
C:\Set-AzureVM.ps1 -Name <String> -Stop [<CommonParameters>]
Just to close this out... I wound up changing this a bit (needs changed and so did the code). As others suggested, I agree that what I was trying to do probably wasn't possible anyway. Also, I am handling the possibility that the user will choose both -Start and -Stop or neither in code. Thanks to everyone for your comments!
SYNTAX
C:\Set-AzureVM.ps1 -Name <String> -ResourceGroup <String> [-Start] [-Stop] [<CommonParameters>]
C:\Set-AzureVM.ps1 -File <String> [-Start] [-Stop] [<CommonParameters>]
ValidateSet('Stop','Start'). You can also just have both with logic in the script that handles the discrepancy. I feel you can't do what you want with the number of parameters you have.