Paramater validation - size in MB

Welcome Forums General PowerShell Q&A Paramater validation - size in MB

Viewing 4 reply threads
  • Author
    Posts
    • #182766
      Participant
      Topics: 9
      Replies: 37
      Points: 162
      Helping Hand
      Rank: Participant

      I'm writing a function to set values for Exchange (quotas, etc.) – using the set-mailbox cmdlet in a larger script.

      Anyone know how to validate a parameter input is a size (like 100MB, 2GB, etc.)?

    • #182787
      Participant
      Topics: 6
      Replies: 108
      Points: 302
      Helping Hand
      Rank: Contributor

      Use a regular expression:

      PS E:\> "100MB" -match '[. 0-9]+(KB|MB|GB)'
      True
      PS E:\> "99GB" -match '[. 0-9]+(KB|MB|GB)'
      True
      PS E:\> "987HB" -match '[. 0-9]+(KB|MB|GB)'
      False

      Credit for the regex goes here: https://www.regextester.com/108417

    • #182790
      Participant
      Topics: 9
      Replies: 37
      Points: 162
      Helping Hand
      Rank: Participant

      Perfect!  That's what I needed.  Thank you.

              [Parameter()]
                  [ValidateScript({
                      if($_ -notmatch '[. 0-9]+(KB|MB|GB)') {throw "Invalid value"} 
                      return $true
                  })]
                  [string]$IssueWarningQuota
      
    • #182796
      Participant
      Topics: 2
      Replies: 511
      Points: 1,306
      Helping Hand
      Rank: Community Hero

      @Darwin-Reiswig might be good to use `[ValidatePattern()]` here instead:

      function Test-Function {
          [CmdletBinding()]
          param(
              [Parameter()]
              [ValidatePattern('[. 0-9]+(KB|MB|GB)')]
              [string]
              $IssueWarningQuota
          )
      < # ... #>
      }
    • #182940
      Participant
      Topics: 9
      Replies: 37
      Points: 162
      Helping Hand
      Rank: Participant

      Slick. I've never used validatepattern before. Learned something new today 🙂

      Thanks!

Viewing 4 reply threads
  • You must be logged in to reply to this topic.