Advertisement
cwprogram

Function Parameter Validation With Parameter Attributes

Jul 11th, 2011
289
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function Test-ValidIp($ipaddress)
  2. {
  3.     try {
  4.         [System.Net.IPAddress]::Parse($ipaddress) | Out-Null
  5.         return $true;
  6.     }
  7.     catch {
  8.         return $false;
  9.     }
  10. }
  11.  
  12. function Use-IpAddress
  13. {
  14.     Param
  15.     (
  16.         [parameter(Mandatory=$true,
  17.                     HelpMessage="Enter an IP Address")]
  18.         [ValidateScript({Test-ValidIp $_})]
  19.         [String]
  20.         $IpAddress
  21.     )
  22.    
  23.     # Work with $ipaddress here
  24. }
  25.  
  26. # Works fine
  27. Use-IpAddress -IpAddress "192.168.1.3"
  28. # Prompts for IPAddress
  29. Use-IPAddress
  30. # Throws Error
  31. Use-IpAddress -IpAddress "garbage"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement