You do this with parametersets.

If that isn't enough of a hint, let me know; and I'll send you some examples.

-----Original Message-----
From: Ben Scott [mailto:mailvor...@gmail.com] 
Sent: Friday, April 12, 2013 5:20 PM
To: NT System Admin Issues
Subject: PowerShell - Dependent parameters

Hey all,

  Is it possible to tell PowerShell that a parameter should be considered 
mandatory *if and only if* another parameter is present?

  Scenario: I've got a script that can optionally send email (Zawinski's Law).  
If the -mailTo parameter is specified, it sends mail.  If that parameter is 
specified, the -smtpHost parameter also needs to be specified.  So -smtpHost 
should be considered mandatory, but *only* if -mailTo is specified.  Otherwise, 
-smtpHost does not need to be present (and, indeed, is pointless).  I figure 
this should employ Parameter Sets somehow, but I can't get it to DWIM.  Simply 
specifying the two parameters as having the same parameter set doesn't make the 
one mandatory.  If I specify either parameter (or both) as Mandatory=$true, it 
becomes mandatory *always*, not just when -mailTo is present.

  I could just test smtpHost explicitly, and abort the script if it's not set, 
but the PowerShell mindset seems to be that parameters should be described, and 
then the runtime does all that for you.  Maybe it just can't do this.

  Currently using PowerShell 2.0, on Win 7 and 2008 R2.

  Here's my Param block, if it helps:

[CmdletBinding()]
Param(

    # things to back up
    [Parameter(Mandatory=$true)] [string] $include,

    # disk or network path to backup to
    [Parameter(Mandatory=$true)] [string] $backupTo,

    # directory to put log files in
    [Parameter(Mandatory=$true)] [string] $logDir,

    # email address to mail report to
    [Parameter(Mandatory=$false,ParameterSetName='mailTo')] [string] $mailTo,

      # SMTP host used to send email
    [Parameter(Mandatory=$false,ParameterSetName='mailTo')] [string] $smtpHost,

    # option, eject media when done
    [Parameter()] [switch] $eject = $false,

)

-- Ben

~ Finally, powerful endpoint security that ISN'T a resource hog! ~ ~ 
<http://www.sunbeltsoftware.com/Business/VIPRE-Enterprise/>  ~

---
To manage subscriptions click here: 
http://lyris.sunbelt-software.com/read/my_forums/
or send an email to listmana...@lyris.sunbeltsoftware.com
with the body: unsubscribe ntsysadmin

~ Finally, powerful endpoint security that ISN'T a resource hog! ~
~ <http://www.sunbeltsoftware.com/Business/VIPRE-Enterprise/>  ~

---
To manage subscriptions click here: 
http://lyris.sunbelt-software.com/read/my_forums/
or send an email to listmana...@lyris.sunbeltsoftware.com
with the body: unsubscribe ntsysadmin

Reply via email to