The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →How do I validate PowerShell input? Put a validation attribute in the parameter declaration that matches the rule: use ValidateSet for fixed choices, ValidateRange for numeric bounds, or a purpose-built attribute for other constraints. PowerShell checks supplied parameter values before running the function or cmdlet, and reports an error when a value fails. This guide explains how to choose and apply the built-in attributes, including important null, type-conversion, and collection edge cases.
How parameter validation works
Validation attributes declare the values a parameter accepts. During parameter binding, PowerShell checks supplied input against those rules before invoking the function or cmdlet. Invalid input produces an error instead of being passed to the function body. See Microsoft Learn’s Validating Parameter Input overview and about_Functions_Advanced_Parameters.
How do I validate a parameter in PowerShell? Add the appropriate attribute inside the parameter declaration, before the parameter’s type. For example, [ValidateRange(1, 90)] [int] $Days makes the allowed numeric interval part of the parameter contract. Validation attributes can also constrain variables; for a typed variable, place the attribute before the type so validation follows type conversion rather than occurring first.
Choose an attribute for the shape of the rule
| Input rule | Attribute | What it checks |
|---|---|---|
| One of a closed list of choices | ValidateSet |
Accepts only listed values and supports tab completion. |
| Numeric minimum and maximum | ValidateRange |
Requires a value within the specified bounds. |
| Minimum and maximum text length | ValidateLength |
Checks the string’s character count against the bounds. |
| Required text format | ValidatePattern |
Matches a regular expression. Use ^ and $ anchors when the entire string, rather than a substring, must match. |
| Minimum and maximum collection size | ValidateCount |
Checks the number of arguments or elements. |
| A custom acceptance condition | ValidateScript |
Runs a script block against the candidate value. |
| Reject null | ValidateNotNull |
Rejects $null, subject to type conversion behavior. |
| Reject null and empty input | ValidateNotNullOrEmpty |
Rejects $null, an empty string, and an empty array. |
| Restrict the drive in a path | ValidateDrive |
Checks the path’s drive portion; it does not establish that the remainder of the path exists. |
Microsoft’s advanced-parameter reference and attribute type reference document these constraints. Select the narrowest attribute that expresses the actual contract; a format check, for example, is not a substitute for checking whether a path exists.
#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
Common parameter declarations
Limit a parameter to named choices
Use ValidateSet when the accepted values form a genuinely closed list. It rejects other values and provides tab completion in supported command-line use. When the choices need to be generated dynamically, the documentation describes IValidateSetValuesGenerator, available starting with PowerShell 6.0; check the target environment before using that interface. See Microsoft Learn’s advanced-parameter guidance and argument completion reference.
Set numeric bounds or text length
ValidateRange communicates numeric limits directly in the declaration. ValidateLength is for a string whose character count must remain within specified bounds. Use these when the bounds are stable parts of the parameter’s contract rather than incidental checks buried in the function body.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
Check a text pattern
ValidatePattern applies a regular expression. Regex patterns can match only part of a string unless you anchor them. For whole-value validation, use a pattern shaped like ^[A-Z]{3}d{4}$; adapt the expression to the actual format rather than treating this illustrative pattern as a universal identifier rule.
Constrain a collection’s size
ValidateCount is appropriate when the number of supplied elements itself is part of the rule. It is distinct from validation of the contents: use an additional suitable constraint if individual values also need to meet a requirement.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
Use ValidateScript only for custom rules
ValidateScript evaluates a script block with the candidate value available as $_. A result of $false fails validation, as does an exception. For example, a script condition can check a property or a relationship between values that a simpler built-in attribute cannot express. Keep custom validation focused on acceptance; the function body can still handle the work of using an accepted value.
There are two important constraints: $null cannot be passed to ValidateScript for validation, and when the attribute is applied to a collection, every element must satisfy the script block. These behaviors are documented in Microsoft Learn’s about_Functions_Advanced_Parameters.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Handle null, empty, and whitespace deliberately
These inputs are not interchangeable. ValidateNotNull rejects null, but a null value assigned to a string parameter can be converted to an empty string. If neither null nor empty strings are meaningful, ValidateNotNullOrEmpty states that intent more clearly; it also rejects an empty array.
An empty string and a whitespace-only string are different: the latter contains characters. The current advanced-parameter documentation also describes ValidateNotNullOrWhiteSpace for rejecting whitespace-only text. Because available attributes can vary by PowerShell version, verify support in the version where the function will run before relying on it.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Put attributes before types and treat defaults separately
For typed parameters and variables, put the validation attribute before the type, as in [ValidateNotNullOrEmpty()] [string] $OutputPath. Microsoft documents that placing a validation attribute after the type can make validation happen before type conversion and lead to unexpected failures.
Parameter validation applies to supplied input; a default value in the declaration is not validated as though it had been supplied by the caller. If a default must satisfy a rule, do not infer that simply from attaching an attribute to the parameter—ensure the value is established and checked through an appropriate design.
Putting the attributes together
This illustrative function combines a closed set, a numeric range, and a nonempty string requirement:
function Get-Report {
param(
[Parameter(Mandatory)]
[ValidateSet('Daily', 'Weekly', 'Monthly')]
[string] $Period,
[ValidateRange(1, 90)]
[int] $Days = 7,
[ValidateNotNullOrEmpty()]
[string] $OutputPath
)
# Function body
}
Period is limited to declared report intervals, Days has numeric bounds, and an empty output path is rejected when supplied. The default of 7 is not proof that parameter binding validated the default; defaults are not validated as supplied parameter input.
Quick Recap
Practical checks before relying on a rule
- Use a finite set only when new values should actually be rejected; use dynamic set generation when the allowed choices need to be computed.
- For patterns, decide whether a substring match is sufficient or the complete input must match, and anchor the regex for the latter.
- Decide separately whether null, empty string, empty collection, or whitespace-only text is invalid.
- For custom script validation, account for null behavior and whether the candidate can be a collection whose elements are checked individually.
- Confirm version support for newer attributes or dynamic value generation on the PowerShell installations that will run the function.
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

