[apols if this appears twice, I submitted before but it didn’t show up on the list]
Hi,
I have a function which I want to set up. I would like the function to either take the -e or -f switches, but not both.
e.g.
foo -e = OK
foo -f = OK, but then would need a mandatory filename input
foo -f filename = OK
foo -e filename = not-OK
foo -e -f = not-OK as the foo function should either work in e-mode or f-mode.
foo -f -e = not-OK
foo -f filename -e = not OK
Here is what I have so far, but it doesn’t do what I need, as it doesn’t force only one switch, (and then if the switch is -f it should force a filename input)
function scrap-Item
{
[CmdletBinding()]
param (
#[Parameter (Mandatory=$true)]
[string] $input,
[switch] $extensionmode,
[switch] $filemode
)
if ($extensionmode)
{
write-output "Executing Script in Extension mode"
if ($input -ne "")
{
write-output "Scrapping $input"
$files = Get-ChildItem -Path 'T:\Downloads' | where {$_.Extension -eq $input}
$shell = New-Object -ComObject 'Shell.Application'
ForEach ($file in $files)
{
$shell.NameSpace(0).ParseName($file.FullName).InvokeVerb('delete')
}
}
else {Write-Output "empty input"}
}
else {Write-Output "executing script in null mode"}
}
Thanks for the swift response Fredrik. Slightly disappointing that PS doesn’t handle natively but your answer looks great as a workaround.
What do you suggest regarding making the $input parameter mandatory if using -f (filemode), but not -e (extensionmode)?
I could do a similar throw statement I guess but was interested in understanding if parameters can be made “conditionally mandatory” in the definition vs. later in the script.
Parameter sets are definitely the way to go. PowerShell v6 may get the option of declaring 2 parameters to be mutually exclusive but the way that functionality will work is still under debate